이전글
https://greed-yb.tistory.com/288
util.class
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JwtTokenUtil {
private static final String SECRET_KEY = "jwttoken_secret_key";
private static final String REFRESH_SECRET_KEY = "jwttoken_refresh_secret_key";
private static final long ACCESS_TOKEN_EXPIRATION = 60 * 60 * 1000; // 60분
private static final long REFRESH_TOKEN_EXPIRATION = 7 * 24 * 60 * 60 * 1000; // 7일
// private static final long ACCESS_TOKEN_EXPIRATION = 1 * 60 * 1000; // 1분
// private static final long REFRESH_TOKEN_EXPIRATION = 5 * 60 * 1000; // 5분
// Access Token 생성
public String generateAccessToken(String username) {
return JWT.create()
.withSubject(username)
.withExpiresAt(new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRATION))
.sign(Algorithm.HMAC512(SECRET_KEY.getBytes()));
}
// Refresh Token 생성
public String generateRefreshToken(String username) {
return JWT.create()
.withSubject(username)
.withExpiresAt(new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRATION))
.sign(Algorithm.HMAC512(REFRESH_SECRET_KEY.getBytes()));
}
// 검증 된 Access Token 에서 username 추출
public String getUsernameFromAccessToken(String token) {
DecodedJWT jwt = JWT.require(Algorithm.HMAC512(SECRET_KEY.getBytes()))
.build()
.verify(token);
return jwt.getSubject();
}
// 검증 된 Refresh Token 에서 username 추출
public String getUsernameFromRefreshToken(String token) {
DecodedJWT jwt = JWT.require(Algorithm.HMAC512(REFRESH_SECRET_KEY.getBytes()))
.build()
.verify(token);
return jwt.getSubject();
}
// 유효한 Access Token 인지 검증
public boolean validateAccessToken(String token) {
try {
JWT.require(Algorithm.HMAC512(SECRET_KEY.getBytes()))
.build()
.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
// 유효한 Refresh Token 인지 검증
public boolean validateRefreshToken(String token) {
try {
JWT.require(Algorithm.HMAC512(REFRESH_SECRET_KEY.getBytes()))
.build()
.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
}
'개발 > Security' 카테고리의 다른 글
[SpringBoot] Security + JWT(Access , Refresh) - Handler (0) | 2024.09.25 |
---|---|
[SpringBoot] Security + JWT(Access , Refresh) - JwtAuthenticationFilter (0) | 2024.09.25 |
[SpringBoot] Security + JWT(Access , Refresh) - SecurityConfig (0) | 2024.09.25 |
[SpringBoot] SecurityConfig - 동적 권한 체크 (0) | 2024.08.02 |
[SpringBoot] Security 로그인 인증, 인가(9) - 실행하기 (0) | 2023.04.30 |
댓글