Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Refactor] #240 - 로그인 로직 리팩토링 #242

Merged
merged 3 commits into from
Mar 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,4 @@ public ResponseEntity<?> modifyProfile(@LoginUser Long userId,
@Operation(summary = "프로필 조회")
public ResponseEntity<MoonshotResponse<UserInfoResponse>> getMyProfile(@LoginUser Long userId);

@ApiResponse(responseCode = "200", description = "구글 로그인에 성공하였습니다.")
@Operation(summary = "구글 로그인")
public String authTest(HttpServletRequest request, HttpServletResponse response);

}
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,6 @@
@RequestMapping("/v1/user")
public class UserController implements UserApi {

@Value("${google.client-id}")
private String googleClientId;

@Value("${google.client-secret}")
private String googleClientSecret;

@Value("${google.redirect-url}")
private String googleRedirectUrl;

private final UserService userService;

@PostMapping("/login")
Expand Down Expand Up @@ -84,18 +75,4 @@ public ResponseEntity<MoonshotResponse<UserInfoResponse>> getMyProfile(@LoginUse
return ResponseEntity.ok(MoonshotResponse.success(SuccessType.GET_PROFILE_SUCCESS, userService.getMyProfile(userId)));
}

@GetMapping("/googleLogin")
@Logging(item = "User", action = "Get")
public String authTest(final HttpServletRequest request, final HttpServletResponse response) {
String redirectURL = "https://accounts.google.com/o/oauth2/v2/auth?client_id=" + googleClientId
+ "&redirect_uri=" + googleRedirectUrl + "&response_type=code&scope=email profile";
try {
response.sendRedirect(redirectURL);
} catch (Exception e) {
log.info("authTest = {}", e);
}

return "SUCCESS";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public SocialLoginResponse login(final SocialLoginRequest request) throws IOExce
};
}

public SocialLoginResponse googleLogin(final SocialLoginRequest request) throws IOException {
public SocialLoginResponse googleLogin(final SocialLoginRequest request) {
GoogleTokenResponse tokenResponse = googleAuthApiClient.googleAuth(
request.code(),
googleClientId,
Expand Down
39 changes: 19 additions & 20 deletions moonshot-auth/src/main/java/org/moonshot/jwt/JwtTokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ public String generateAccessToken(Long userId) {
.setExpiration(new Date(now.getTime() + JWTConstants.ACCESS_TOKEN_EXPIRATION_TIME));

claims.put(JWTConstants.USER_ID, userId);
claims.put(JWTConstants.TOKEN_TYPE, JWTConstants.ACCESS_TOKEN);

return Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
Expand All @@ -74,6 +75,7 @@ public String generateRefreshToken(Long userId) {
.setExpiration(new Date(now.getTime() + JWTConstants.REFRESH_TOKEN_EXPIRATION_TIME));

claims.put(JWTConstants.USER_ID, userId);
claims.put(JWTConstants.TOKEN_TYPE, JWTConstants.REFRESH_TOKEN);

String refreshToken = Jwts.builder()
.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
Expand All @@ -95,10 +97,25 @@ private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(encodedKey.getBytes());
}

public JwtValidationType validateAccessToken(String token) {
public Long validateRefreshToken(String refreshToken) {
validateToken(refreshToken);
Long userId = getUserFromJwt(refreshToken);
if (redisTemplate.hasKey(String.valueOf(userId))) {
return userId;
} else {
throw new InvalidRefreshTokenException();
}
}

public JwtValidationType validateToken(String token) {
try {
final Claims claims = getBody(token);
return JwtValidationType.VALID_JWT;
if (claims.get(JWTConstants.TOKEN_TYPE).toString().equals(JWTConstants.ACCESS_TOKEN)) {
return JwtValidationType.VALID_ACCESS;
} else if (claims.get(JWTConstants.TOKEN_TYPE).toString().equals(JWTConstants.REFRESH_TOKEN)) {
return JwtValidationType.VALID_REFRESH;
}
throw new MoonshotException(ErrorType.WRONG_TYPE_TOKEN_ERROR);
} catch (MalformedJwtException e) {
throw new MoonshotException(ErrorType.WRONG_TYPE_TOKEN_ERROR);
} catch (ExpiredJwtException e) {
Expand All @@ -112,15 +129,6 @@ public JwtValidationType validateAccessToken(String token) {
}
}

public Long validateRefreshToken(String refreshToken) {
Long userId = getUserFromJwt(refreshToken);
if (redisTemplate.hasKey(String.valueOf(userId))) {
return userId;
} else {
throw new InvalidRefreshTokenException();
}
}

public void deleteRefreshToken(Long userId) {
if (redisTemplate.hasKey(String.valueOf(userId))) {
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
Expand All @@ -130,15 +138,6 @@ public void deleteRefreshToken(Long userId) {
throw new InvalidRefreshTokenException();
}
}

private Claims parseClaims(String accessToken) {
try {
return Jwts.parserBuilder().setSigningKey(JWT_SECRET).build().parseClaimsJws(accessToken).getBody();
} catch (ExpiredJwtException e) {
return e.getClaims();
}
}

private Claims getBody(final String token) {
return Jwts.parserBuilder()
.setSigningKey(getSigningKey())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package org.moonshot.jwt;

public enum JwtValidationType {
VALID_JWT,
VALID_ACCESS,
VALID_REFRESH,
INVALID_JWT_SIGNATURE,
INVALID_JWT_TOKEN,
EXPIRED_JWT_TOKEN,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.moonshot.constants.JWTConstants;
import org.moonshot.constants.WhiteListConstants;
import org.moonshot.jwt.JwtTokenProvider;
import org.moonshot.jwt.JwtValidationType;
Expand All @@ -33,11 +34,11 @@ protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull Ht
}
}
final String token = getJwtFromRequest(request);
if (jwtTokenProvider.validateAccessToken(token) == JwtValidationType.VALID_JWT) {
Long userId = jwtTokenProvider.getUserFromJwt(token);
Authentication authentication = jwtTokenProvider.getAuthentication(userId);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
jwtTokenProvider.validateToken(token);

Long userId = jwtTokenProvider.getUserFromJwt(token);
Authentication authentication = jwtTokenProvider.getAuthentication(userId);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(request, response);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@
public class JWTConstants {

public static final String USER_ID = "userId";
public static final String TOKEN_TYPE = "type";
public static final String ACCESS_TOKEN = "access";
public static final String REFRESH_TOKEN = "refresh";
public static final Long ACCESS_TOKEN_EXPIRATION_TIME = 60 * 1000L * 20;
public static final Long REFRESH_TOKEN_EXPIRATION_TIME = 60 * 1000L * 60 * 24 * 7 * 2;

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@

public class InvalidRefreshTokenException extends MoonshotException {
public InvalidRefreshTokenException() {
super(ErrorType.INVALID_REFRESHTOKEN_ERROR);
super(ErrorType.INVALID_REFRESH_TOKEN_ERROR);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public enum ErrorType {
INVALID_AUTHORIZATION_ERROR(HttpStatus.UNAUTHORIZED, "유효하지 않은 인증 코드입니다."),
UNSUPPORTED_TOKEN_ERROR(HttpStatus.UNAUTHORIZED,"지원하지 않는 토큰 방식입니다."),
INVALID_ACCESS_TOKEN_ERROR(HttpStatus.UNAUTHORIZED, "유효하지 않은 AccessToken입니다."),
INVALID_REFRESHTOKEN_ERROR(HttpStatus.UNAUTHORIZED, "유효하지 않은 RefreshToken입니다."),
INVALID_REFRESH_TOKEN_ERROR(HttpStatus.UNAUTHORIZED, "유효하지 않은 RefreshToken입니다."),
INVALID_AUTH_ERROR(HttpStatus.UNAUTHORIZED, "인증되지 않은 사용자입니다."),
EXPIRED_TOKEN_ERROR(HttpStatus.UNAUTHORIZED, "만료된 Token입니다."),
WRONG_TYPE_TOKEN_ERROR(HttpStatus.UNAUTHORIZED, "잘못된 형식의 Token입니다"),
Expand Down
Loading