-
Notifications
You must be signed in to change notification settings - Fork 2
Feat : 커스텀 JWT Provider 구현 #279
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| package org.terning.terningserver.auth.dto; | ||
|
|
||
| public record Token(String accessToken, String refreshToken) { | ||
| } |
85 changes: 85 additions & 0 deletions
85
src/main/java/org/terning/terningserver/auth/jwt/JwtProvider.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| package org.terning.terningserver.auth.jwt; | ||
|
|
||
| import io.jsonwebtoken.*; | ||
| import io.jsonwebtoken.security.Keys; | ||
| import jakarta.annotation.PostConstruct; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.stereotype.Component; | ||
| import org.terning.terningserver.auth.dto.Token; | ||
| import org.terning.terningserver.common.config.ValueConfig; | ||
| import org.terning.terningserver.auth.jwt.exception.JwtErrorCode; | ||
|
|
||
| import javax.crypto.SecretKey; | ||
| import java.util.Date; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class JwtProvider { | ||
|
|
||
| private static final String USER_ID_CLAIM = "userId"; | ||
| private static final String TOKEN_PREFIX = "Bearer "; | ||
|
|
||
| private final ValueConfig valueConfig; | ||
| private SecretKey secretKey; | ||
|
|
||
| @PostConstruct | ||
| protected void init() { | ||
| secretKey = Keys.hmacShaKeyFor(valueConfig.getSecretKey().getBytes()); | ||
| } | ||
|
|
||
| public Token generateTokens(Long userId) { | ||
| String accessToken = generateToken(userId, valueConfig.getAccessTokenExpired()); | ||
| String refreshToken = generateToken(userId, valueConfig.getRefreshTokenExpired()); | ||
| return new Token(accessToken, refreshToken); | ||
| } | ||
|
|
||
| public Token generateAccessToken(Long userId) { | ||
| String accessToken = generateToken(userId, valueConfig.getAccessTokenExpired()); | ||
| return new Token(accessToken, null); | ||
| } | ||
|
|
||
| public Long getUserIdFrom(String authorizationHeader) { | ||
| String token = resolveToken(authorizationHeader); | ||
|
|
||
| Claims claims = parseClaims(token); | ||
|
|
||
| Object userIdClaim = claims.get(USER_ID_CLAIM); | ||
| if (userIdClaim instanceof Number) { | ||
| return ((Number) userIdClaim).longValue(); | ||
| } | ||
| throw new JwtException(JwtErrorCode.INVALID_USER_ID_TYPE.getMessage()); | ||
| } | ||
|
|
||
| public String resolveToken(String rawToken) { | ||
| if (rawToken != null && rawToken.startsWith(TOKEN_PREFIX)) { | ||
| return rawToken.substring(TOKEN_PREFIX.length()); | ||
| } | ||
| throw new JwtException(JwtErrorCode.TOKEN_NOT_FOUND.getMessage()); | ||
| } | ||
|
|
||
| private String generateToken(Long userId, long expiration) { | ||
| Claims claims = Jwts.claims(); | ||
| claims.put(USER_ID_CLAIM, userId); | ||
|
|
||
| return Jwts.builder() | ||
| .setClaims(claims) | ||
| .setIssuedAt(new Date()) | ||
| .setExpiration(new Date(System.currentTimeMillis() + expiration)) | ||
| .signWith(secretKey) | ||
| .compact(); | ||
| } | ||
|
|
||
| private Claims parseClaims(String token) { | ||
| try { | ||
| return Jwts.parserBuilder() | ||
| .setSigningKey(secretKey) | ||
| .build() | ||
| .parseClaimsJws(token) | ||
| .getBody(); | ||
| } catch (ExpiredJwtException e) { | ||
| throw new JwtException(JwtErrorCode.EXPIRED_JWT_TOKEN.getMessage()); | ||
| } catch (UnsupportedJwtException | MalformedJwtException | SecurityException | IllegalArgumentException e) { | ||
| throw new JwtException(JwtErrorCode.INVALID_JWT_TOKEN.getMessage()); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 1 addition & 1 deletion
2
.../security/jwt/exception/JwtException.java → ...rver/auth/jwt/exception/JwtException.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
4 changes: 2 additions & 2 deletions
4
src/main/java/org/terning/terningserver/common/security/jwt/auth/UserIdConverter.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Specify a charset when converting the secret key string to bytes, e.g.,
getSecretKey().getBytes(StandardCharsets.UTF_8), to avoid platform-default encoding differences.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
피드백 감사합니다!
getSecretKey().getBytes()처럼 문자열을 바이트로 변환할 때 Charset을 명시하지 않으면, OS에 따라 기본 인코딩이 달라져 예상치 못한 인증 오류를 발생시킬 수 있는 중요한 부분을 잘 짚어주신 것 같아요!마침
ValueConfig의 init() 메소드에서는 이미StandardCharsets.UTF_8을 사용해 Base64 인코딩을 하고 있었는데, JwtProvider에서는 이 부분을 놓치고 있었네요.두 클래스 간의 역할을 명확히 하고 일관성을 유지하기 위해,
ValueConfig에서는 Base64 인코딩 로직을 제거하고, JwtProvider의 init() 메소드에서 제안해주신 대로 StandardCharsets.UTF_8을 명시하여 SecretKey를 생성하도록 수정하겠습니다. 이렇게 하면 SecretKey 생성 책임이 JwtProvider로 일원화되어 코드가 더 명확해질 것 같네요!꼼꼼한 리뷰 감사합니다!