Spring Boot에서 JWT 생성 및 검증 간단히 구현
1. 개발환경
- Java 11
- Spring Boot 2.5.5
2. Gradle dependencies
dependencies {
implementation 'io.jsonwebtoken:jjwt-api:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.2'
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.2'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
3. JWS(서명한 JWT) 생성
1) JwtUtil
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.security.Key;
public class JwtUtil {
// 최소 32자리(256bit)
private final String RAW_SECRET_KEY = "aaaabbbbccccddddeeeeffffgggghhhh";
private final String SAMPLE_SUBJECT = "tunaguy";
public String createJws() {
Key key = Keys.hmacShaKeyFor(RAW_SECRET_KEY.getBytes(StandardCharsets.UTF_8));
String jws = Jwts.builder()
.setSubject(SAMPLE_SUBJECT)
.signWith(key)
.compact();
return jws;
}
}
2) 생성된 JWS
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0dW5hZ3V5In0.qT08o0iNljPfPdWqg8P25c0wrfsmf9hTha4Re7hOTh0
// Header
{
"alg": "HS256"
}
// PAYLOAD
{
"sub": "tunaguy"
}
4. JWS 검증
1) 업데이트 된 JwtUtil
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.security.Key;
public class JwtUtil {
// 최소 32자리(256bit)
private final String RAW_SECRET_KEY = "aaaabbbbccccddddeeeeffffgggghhhh";
private final String SAMPLE_SUBJECT = "tunaguy";
public String createJws() {
Key key = Keys.hmacShaKeyFor(RAW_SECRET_KEY.getBytes(StandardCharsets.UTF_8));
String jws = Jwts.builder()
.setSubject(SAMPLE_SUBJECT)
.signWith(key)
.compact();
return jws;
}
public boolean isValid(String jws) {
Key key = Keys.hmacShaKeyFor(RAW_SECRET_KEY.getBytes(StandardCharsets.UTF_8));
try {
Jws<Claims> parsed = Jwts.parserBuilder()
.setSigningKey(key)
.build()
.parseClaimsJws(jws);
return parsed.getBody().getSubject().equals(SAMPLE_SUBJECT);
} catch (JwtException e) {
return false;
}
}
}
5. Test 코드
import com.example.jjwt.util.JwtUtil;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class JwtUtilTest {
@Test
void isValid_success() {
JwtUtil util = new JwtUtil();
String jws = util.createJws();
Assertions.assertTrue(util.isValid(jws));
}
}
6. 더 많은 정보를 알고싶으면?
GitHub - jwtk/jjwt: Java JWT: JSON Web Token for Java and Android
README.md 에 매우 친절하게 정리되어 있습니다.
댓글