Skip to content

Commit

Permalink
refactor: 토큰 정보 수정
Browse files Browse the repository at this point in the history
- 액세스 토큰 : 만료 정보를 제외
- 리프레쉬 토큰 : 랜덤 UUID를 반환
  • Loading branch information
SJ70 committed Jul 25, 2024
1 parent 5d11524 commit 2174989
Showing 1 changed file with 4 additions and 21 deletions.
25 changes: 4 additions & 21 deletions src/main/java/com/j9/bestmoments/jwt/JwtTokenProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Collections;
import java.util.Date;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
Expand All @@ -26,40 +27,22 @@ public class JwtTokenProvider {

private final Key key;

@Value("${jwt.accessTokenExpirationMs}")
private long accessTokenExpirationMs;

@Value("${jwt.refreshTokenExpirationMs}")
private long refreshTokenExpirationMs;

// secret 값을 암호화 (SHA 키 생성)
public JwtTokenProvider(@Value("${jwt.secret}") String secretKey) {
byte[] keyBytes = Decoders.BASE64.decode(secretKey);
this.key = Keys.hmacShaKeyFor(keyBytes);
}

public String generateAccessToken(Member member) {
Date now = new Date();
Date accessTokenExpiresIn = new Date(now.getTime() + accessTokenExpirationMs);
return Jwts.builder()
.claim("id", member.getId())
.claim("role", member.getRole().getValue())
.setIssuedAt(now)
.setExpiration(accessTokenExpiresIn)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}

public String generateRefreshToken(Member member) {
Date now = new Date();
Date refreshTokenExpiresIn = new Date(now.getTime() + refreshTokenExpirationMs);
return Jwts.builder()
.claim("id", member.getId())
.claim("role", member.getRole().getValue())
.setIssuedAt(now)
.setExpiration(refreshTokenExpiresIn)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
return UUID.randomUUID().toString();
}

// 토큰을 복호화하여 인증 정보 추출
Expand All @@ -71,7 +54,7 @@ public Authentication getAuthentication(String accessToken) {
.getBody();

if (claims.get("id") == null || claims.get("role") == null) {
throw new RuntimeException("권한 정보가 없는 토큰입니다.");
throw new AccessDeniedException("권한 정보가 없는 토큰입니다.");
}

String id = claims.get("id").toString();
Expand Down

0 comments on commit 2174989

Please sign in to comment.