Skip to content

Commit

Permalink
Merge pull request #27 from KNU-HAEDAL-Website/racator-modify-login-a…
Browse files Browse the repository at this point in the history
…rg-issue-14

refactor: 로그인 요청 타입 Json 변경 및 username 인자를 userId로 변경 (#14)
  • Loading branch information
tfer2442 authored Apr 18, 2024
2 parents ef75e30 + 2e8a2f2 commit d042498
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 15 deletions.
3 changes: 2 additions & 1 deletion src/main/java/com/haedal/haedalweb/constants/ErrorCode.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
@Getter
public enum ErrorCode {
DUPLICATED_USER_ID(HttpStatus.CONFLICT, "중복된 아이디가 존재합니다."),
DUPLICATED_STUDENT_NUMBER(HttpStatus.CONFLICT, "중복된 학번이 존재합니다.");
DUPLICATED_STUDENT_NUMBER(HttpStatus.CONFLICT, "중복된 학번이 존재합니다."),
INVALID_LOGIN_CONTENTS_TYPE(HttpStatus.BAD_REQUEST, "지원하지 않는 형식입니다.");

private final HttpStatus httpStatus;
private final String message;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package com.haedal.haedalweb.constants;

import java.util.concurrent.TimeUnit;

public final class LoginConstants {
public static final String REFRESH_TOKEN_NULL = "refresh token null";
public static final String REFRESH_TOKEN_EXPIRED = "refresh token expired";
Expand All @@ -13,7 +11,7 @@ public final class LoginConstants {
public static final String REFRESH_TOKEN = "refreshToken";
public static final String ACCESS_TOKEN = "Authorization";

public static final String USERNAME_CLAIM = "username";
public static final String USER_ID_CLAIM = "userId";
public static final String ROLE_CLAIM = "role";
public static final String CATEGORY_CLAIM = "category";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,14 @@ public ResponseEntity<?> reissue(HttpServletRequest request, HttpServletResponse
return new ResponseEntity<>("invalid refresh token", HttpStatus.BAD_REQUEST);
}

String username = jwtUtil.getUsername(refreshToken);
String userId = jwtUtil.getUserId(refreshToken);
String role = jwtUtil.getRole(refreshToken);
//make new JWT
String newAccessToken = jwtUtil.createJwt(LoginConstants.ACCESS_TOKEN, username, role, LoginConstants.ACCESS_TOKEN_EXPIRATION_TIME_MS);
String newRefreshToken = jwtUtil.createJwt(LoginConstants.REFRESH_TOKEN, username, role, LoginConstants.REFRESH_TOKEN_EXPIRATION_TIME_MS);
String newAccessToken = jwtUtil.createJwt(LoginConstants.ACCESS_TOKEN, userId, role, LoginConstants.ACCESS_TOKEN_EXPIRATION_TIME_MS);
String newRefreshToken = jwtUtil.createJwt(LoginConstants.REFRESH_TOKEN, userId, role, LoginConstants.REFRESH_TOKEN_EXPIRATION_TIME_MS);

redisService.deleteRefreshToken(refreshToken);
redisService.saveRefreshToken(newRefreshToken, username);
redisService.saveRefreshToken(newRefreshToken, userId);

//response
response.setHeader(LoginConstants.ACCESS_TOKEN, newAccessToken);
Expand Down
11 changes: 11 additions & 0 deletions src/main/java/com/haedal/haedalweb/dto/LoginDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.haedal.haedalweb.dto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class LoginDTO {
private String userId;
private String password;
}
2 changes: 1 addition & 1 deletion src/main/java/com/haedal/haedalweb/jwt/JWTFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
return;
}

String userId = jwtUtil.getUsername(accessToken);
String userId = jwtUtil.getUserId(accessToken);
String role = jwtUtil.getRole(accessToken);

UserDetailsDTO userDetailsDTO = UserDetailsDTO.builder()
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/haedal/haedalweb/jwt/JWTUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ public JWTUtil(@Value("${spring.jwt.secret}")String secret) {
secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), Jwts.SIG.HS256.key().build().getAlgorithm());
}

public String getUsername(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get(LoginConstants.USERNAME_CLAIM, String.class);
public String getUserId(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get(LoginConstants.USER_ID_CLAIM, String.class);
}

public String getRole(String token) {
Expand All @@ -36,7 +36,7 @@ public Boolean isExpired(String token) {
public String createJwt(String category, String userId, String role, Long expiredMs) {
return Jwts.builder()
.claim(LoginConstants.CATEGORY_CLAIM, category)
.claim(LoginConstants.USERNAME_CLAIM, userId)
.claim(LoginConstants.USER_ID_CLAIM, userId)
.claim(LoginConstants.ROLE_CLAIM, role)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expiredMs))
Expand Down
26 changes: 23 additions & 3 deletions src/main/java/com/haedal/haedalweb/jwt/LoginFilter.java
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
package com.haedal.haedalweb.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.haedal.haedalweb.constants.ErrorCode;
import com.haedal.haedalweb.constants.LoginConstants;
import com.haedal.haedalweb.dto.ErrorResponse;
import com.haedal.haedalweb.dto.LoginDTO;
import com.haedal.haedalweb.exception.BusinessException;
import com.haedal.haedalweb.service.RedisService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Iterator;

Expand All @@ -27,11 +37,21 @@ public class LoginFilter extends UsernamePasswordAuthenticationFilter {

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
LoginDTO loginDTO;

String username = obtainUsername(request);
String password = obtainPassword(request);
try {
ObjectMapper objectMapper = new ObjectMapper();
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
loginDTO = objectMapper.readValue(messageBody, LoginDTO.class);
} catch (IOException e) {
throw new AuthenticationServiceException(ErrorCode.INVALID_LOGIN_CONTENTS_TYPE.getMessage(), e);
}

UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null);
String userId = loginDTO.getUserId();
String password = loginDTO.getPassword();

UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userId, password, null);

return authenticationManager.authenticate(authToken);
}
Expand Down

0 comments on commit d042498

Please sign in to comment.