Skip to content

Commit

Permalink
refactor: JWT 토큰에서 사용자 ID 추출 로직 개선
Browse files Browse the repository at this point in the history
  • Loading branch information
sseoU committed Oct 30, 2024
1 parent 9023289 commit b13ba1c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 25 deletions.
Original file line number Diff line number Diff line change
@@ -1,14 +1,6 @@
package org.ioteatime.meonghanyangserver.auth.dto.reponse;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import jakarta.validation.constraints.NotNull;
import lombok.*;

@Data
@NoArgsConstructor
@Builder
@AllArgsConstructor
public class RefreshResponse {
private String accessToken;
}
public record RefreshResponse(@NotNull String accessToken) {}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,20 @@ public void send(String email) {
}

public RefreshResponse reissueAccessToken(String authorizationHeader) {
String refreshToken = authorizationHeader.replace("Bearer ", "");
String refreshToken = jwtUtils.extractTokenFromHeader(authorizationHeader);

Long userId = jwtUtils.getIdFromToken(refreshToken);
UserEntity userEntity =
userRepository
.findById(userId)
.orElseThrow(
() ->
new ApiException(
ErrorTypeCode.BAD_REQUEST, "유효하지 않은 사용자입니다."));

if (!jwtUtils.validateToken(refreshToken, userEntity)) {
throw new ApiException(ErrorTypeCode.BAD_REQUEST, "Refresh token이 만료되었거나 유효하지 않습니다.");
}

RefreshToken storedToken =
refreshTokenRepository
Expand All @@ -93,19 +106,6 @@ public RefreshResponse reissueAccessToken(String authorizationHeader) {
throw new ApiException(ErrorTypeCode.BAD_REQUEST, "토큰이 일치하지 않습니다.");
}

String email = jwtUtils.getSubjectFromToken(refreshToken);
UserEntity userEntity =
userRepository
.findByEmail(email)
.orElseThrow(
() ->
new ApiException(
ErrorTypeCode.BAD_REQUEST, "유효하지 않은 사용자입니다."));

if (!jwtUtils.validateToken(refreshToken, userEntity)) {
throw new ApiException(ErrorTypeCode.BAD_REQUEST, "Refresh token이 만료되었습니다.");
}

String newAccessToken = jwtUtils.generateAccessToken(userEntity);

return new RefreshResponse(newAccessToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,13 @@ public boolean validateToken(String token, UserEntity userEntity) {

return subject != null && email != null && subject.equals(email);
}

public String extractTokenFromHeader(String authorizationHeader) {
return authorizationHeader.replace("Bearer ", "");
}

public Long getIdFromToken(String token) {
final Claims claims = getAllClaimsFromToken(token);
return Long.valueOf(String.valueOf(claims.get("jti")));
}
}

0 comments on commit b13ba1c

Please sign in to comment.