겪은 에러
리프레시 토큰으로 액세스 토큰을 재발급 받는 API 설계 중
로그인 성공 후 반환되는 리프레시 토큰을 이용해 바로 액세스 토큰을 새로 발급 해주는 리프레시 API 테스트를 진행했는데 자꾸 유효하지 않은 리프레시 토큰이라고 예외가 발생했다. DB에 들어가는 리프레시 토큰 데이터를 확인해 보니 로그인 후 반환된 토큰 값이 맞았고 만료 시간도 설정한 대로 저장되어 있었다. ! [[ Pasted image 20250409005859.png ]]
로그에 찍히는 토큰 값이랑 DB에 저장된 토큰값이 분명 맞는데.. 예외가 발생하는 이유를 모르겠어서 코드를 하나씩 되집어 보았다.
토큰 만료 시간 설정은
// applcation.yml
jwt:
access-token-expiration: 3600000 # 1시간 (ms 기준)
refresh-token-expiration-days: 7
설정 후
만료 시간 값을 가지는 클래스를 생성해 관리했다.
@Component
@ConfigurationProperties(prefix = "jwt")
@Getter
@Setter
public class JwtProperties {
private long accessTokenExpiration;
private int refreshTokenExpirationDays;
}
JwtUtil 클래스에서 토큰 생성
// JwtUtil
// 액세스 토큰 생성
public String generateAccessToken(String email) {
return Jwts.builder()
.setSubject(email) // username 대신 email 사용
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getAccessTokenExpiration()))
.signWith(accesskey)
.compact();
}
// 리프레시 토큰 생성
public String generateRefreshToken(String email){
return Jwts.builder()
.setSubject(email)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + jwtProperties.getRefreshTokenExpirationDays()))
.signWith(refreshKey)
.compact();
}
문제는 여기였다! 리프레시 토큰 만료 시간이 yml에 설정된 refresh-token-expiration-days: 7! 즉 7이 그대로 들어가서 7밀리초 설정되어 생성하자 마자 만료가 됐던 것.
그래서 수정 일 단위로 저장되어있던 7을 다음과 같이 수정했다.
// 리프레쉬 토큰 생성
public String generateRefreshToken(String email){
long expirationMillis = jwtProperties.getRefreshTokenExpirationDays() * 24 * 60 * 60 * 1000L; // 7일 -> 밀리초
Date expirationDate = new Date(System.currentTimeMillis() + expirationMillis);
return Jwts.builder()
.setSubject(email)
.setIssuedAt(new Date())
.setExpiration(expirationDate)
.signWith(refreshKey)
.compact();
}
그 결과 API 테스트 결과는! ! [[ Pasted image 20250409011421.png ]]
요청 성공.
This line appears after every note.
Notes mentioning this note
There are no notes linking to this note.