이전 글: https://im-diary.tistory.com/120
[JWT] JwtFilter
이전 글: https://im-diary.tistory.com/119 [JWT] Security Config 6.x.xcommon/config/WebSecurityConfig.java (전체코드)@Configuration@EnableWebSecurity@RequiredArgsConstructorpublic class WebSecurityConfig { private final JwtAuthenticationFilter jwtAu
im-diary.tistory.com
생성자
Keys.hmacShaKeyFor(secret.getBytes())
- secret 문자열을 바이트 배열로 변환한 후, hmacShaKeyFor 메서드를 사용하여 HMAC-SHA 알고리즘용 비밀키 객체를 생성
- **Keys.hmacShaKeyFor**는 io.jsonwebtoken.security.Keys 클래스의 메서드로, JWT 서명에 사용되는 SecretKey 객체를 생성
- 이 SecretKey 객체는 JWT의 서명을 생성하거나 검증할 때 사용
- 이 과정에서 사용하는 키는 반드시 HMAC-SHA 알고리즘이 요구하는 최소 길이를 만족해야 합니다. 예를 들어, HMAC-SHA256의 경우 최소 256비트(32바이트)가 필요
@Component
public class JwtProvider {
public SecretKey secretKey;
public JwtProvider(@Value("${jwt.secretKey}") String secret) {
secretKey = Keys.hmacShaKeyFor(secret.getBytes());
}
create (토큰생성)
- 위에서 만들어둔 SecretKey를 사용해서 토큰을 생성
- 아래 코드의 주석 참고
- .claims(): Map으로 여러 값 셋팅 가능 / claim(): 단일 값
public String create(String email, String role) {
Date expiredDate = Date.from(Instant.now().plus(1, ChronoUnit.HOURS)); // 엑세스 토큰 유효시간 1시간
Map<String, String> claimsMap = Map.of("email", email, "role", role);
return Jwts.builder()
.claims(claimsMap) // jwt 토큰 내 정보
.expiration(expiredDate) // 만료시간
.signWith(secretKey) // 암호화
.issuedAt(Date.from(Instant.now())) // 발급 시간
.subject("주제") // 토큰과 관련된 주요 대상
.compact();
}
토큰에서 값 가져오기 및 검증
public String getEmail(String jwt) { // JWT 토큰의 유효성 검사
Claims claims = validateToken().parseSignedClaims(jwt).getPayload();
return claims.get("email", String.class);
}
public String getRole(String jwt) { // JWT 토큰의 유효성 검사
Claims claims = validateToken().parseSignedClaims(jwt).getPayload();
return claims.get("role", String.class);
}
private JwtParser validateToken() {
try{
return Jwts.parser().verifyWith(secretKey).build();
} catch (SecurityException | MalformedJwtException e) {
// 서명 검증 실패 시 처리
throw new IllegalArgumentException("Invalid JWT signature", e);
} catch (ExpiredJwtException e) {
// JWT가 만료된 경우 처리
throw new IllegalArgumentException("Expired JWT token", e);
} catch (Exception e) {
// 기타 예외 처리
throw new IllegalArgumentException("Invalid JWT token", e);
}
}
전체코드
package com.my.cook_recipe.common.provider;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;
@Component
public class JwtProvider {
public SecretKey secretKey;
public JwtProvider(@Value("${jwt.secretKey}") String secret) {
secretKey = Keys.hmacShaKeyFor(secret.getBytes());
}
public String create(String email, String role) {
Date expiredDate = Date.from(Instant.now().plus(1, ChronoUnit.HOURS)); // 엑세스 토큰 유효시간 1시간
Map<String, String> claimsMap = Map.of("email", email, "role", role);
return Jwts.builder()
.claims(claimsMap) // jwt 토큰 내 정보
.expiration(expiredDate) // 만료시간
.signWith(secretKey) // 암호화
.compact();
}
public String getEmail(String jwt) { // JWT 토큰의 유효성 검사
Claims claims = validateToken().parseSignedClaims(jwt).getPayload();
return claims.get("email", String.class);
}
public String getRole(String jwt) { // JWT 토큰의 유효성 검사
Claims claims = validateToken().parseSignedClaims(jwt).getPayload();
return claims.get("role", String.class);
}
private JwtParser validateToken() {
try{
return Jwts.parser().verifyWith(secretKey).build();
} catch (SecurityException | MalformedJwtException e) {
// 서명 검증 실패 시 처리
throw new IllegalArgumentException("Invalid JWT signature", e);
} catch (ExpiredJwtException e) {
// JWT가 만료된 경우 처리
throw new IllegalArgumentException("Expired JWT token", e);
} catch (Exception e) {
// 기타 예외 처리
throw new IllegalArgumentException("Invalid JWT token", e);
}
}
}
기본적인 시큐리티 공부 끝 !
'Spring' 카테고리의 다른 글
[JWT] JwtFilter (1) | 2024.11.20 |
---|---|
[JWT] Security Config 6.x.x (1) | 2024.11.19 |
[JWT] 프로젝트 생성1 (0) | 2024.11.18 |
[Spring] log4jdbc-log4j2 설정 (0) | 2024.07.03 |
POI - 엑셀 라이브러리 (0) | 2024.06.10 |