이번 포스트에서는 HS256을 사용한 JWT 서명 알고리즘을 Spring Boot로 구현해볼 것이다.
private final Key key;
// HMAC SHA 키를 생성
public JwtTokenProvider(@Value("${spring.jwt.secret}") String secretKey) {
this.key = Keys.hmacShaKeyFor(secretKey.getBytes());
}
우선 HMAC SHA 키를 생성한다. @Value("${spring.jwt.secret}") 로 application.properties에 작성된 JWT 시크릿 키를 주입한다. Keys.hmacShaKeyFor(secretKey.getBytes()) 는 제공된 비밀 키 문자열을 HMAC SHA-256 알고리즘에 적합한 형식의 SecretKey 객체로 변환하는 역할을 한다.
// --- Access Token 생성 ---
public String createAccessToken(String userId, long accessTokenValidity, Integer tokenVersion) {
Date now = new Date();
Date expiry = new Date(now.getTime() + accessTokenValidity);
Map<String, Object> claims = new HashMap<>();
claims.put("tokenVersion", tokenVersion); // tokenVersion 클레임 추가
return Jwts.builder()
.setClaims(claims) // 클레임 설정
.setSubject(userId)
.setIssuedAt(now)
.setExpiration(expiry)
.signWith(key, SignatureAlgorithm.HS256)
.compact();
}
Access Token을 생성하는 메서드이다. .signWith(key, SignatureAlgorithm.HS256)를 사용하여 JWT에 서명한다.JWT 헤더의 alg 필드에 "HS256"이라는 값을 명시적으로 포함한다. 이 정보는 검증하는 쪽에서 어떤 알고리즘으로 서명해야하는 지를 알려준다.
SignatureAlgorithm 클래스를 보면 앞 포스트에서 다룬 서명 알고리즘 종류들을 볼 수 있다.

키 타입과 길이를 확인하여 가장 적합한 서명 알고리즘을 찾아 반환한다. 또한 특정 알고리즘에 대한 키가 유효한지 검증할 수 있다.

감사합니다 (╹ڡ╹ )
'Development > Back-end' 카테고리의 다른 글
| [Spring Boot] @Data 알고 쓰기 (0) | 2025.11.26 |
|---|---|
| [Spring Boot] Spring Security + JWT + Redis 로그아웃 구현하기 (0) | 2025.11.12 |
| [JWT] JWT 서명 알고리즘 (1) - HMAC, RSA (0) | 2025.08.18 |
| [Spring Boot] @Scheduled 사용하기 (0) | 2025.08.10 |
| [Spring Boot] Redis를 사용한 로그아웃 구현하기 (0) | 2025.07.23 |