Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Archives
Today
Total
관리 메뉴

아님말고

[JWT] jwt 생성 및 검증 예제 (spring boot + gradle) 본문

Java

[JWT] jwt 생성 및 검증 예제 (spring boot + gradle)

스타박씨 2023. 3. 14. 13:29

 

1. 의존성 추가

	implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
	runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.11.5'
	runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'

 

2. 토큰 만들기 및 검증하기

@Service
public class TokenService {

	private static final String SECRET_KEY = "OnlyICanChangeMyLifeNoOneCanDoItForMe";
	
	/**
	 * 토큰 생성하기
	 * @return
	 */
	public String makeJwtToken() {
		Date now = new Date();
		Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
		
		return Jwts.builder()
				.setHeaderParam(Header.TYPE, Header.JWT_TYPE)
				.setIssuer("myteam")
				.setIssuedAt(now)
				.setExpiration(new Date(now.getTime() + Duration.ofMinutes(30).toMillis()))
				.claim("id", "myId")
				.claim("email", "myId@gmail.com")
				.signWith(key)
				.compact();
	}
	
	/**
	 * 토큰 복호화 하여 본문(Payload) 가져오기
	 * @param token
	 * @return
	 */
	public Claims parseJwtToken(String token) {
		Key key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));
		
		Claims claims = Jwts.parserBuilder()
				.setSigningKey(key)
				.build()
				.parseClaimsJws(token)
				.getBody();
		System.out.println("claims = " + claims.toString());
		
		return claims;
	}
}

 

3. 토큰 헤더에 담아서 보내기

@RestController
public class TokenController {

	@Autowired
	private TokenService tokenService;
	
	@GetMapping("getToken")
	public ResponseEntity<?> getToken(){
		String token = tokenService.makeJwtToken();
		
		HttpHeaders header = new HttpHeaders();
		header.set("Authorization", "Bearer " + token);
		
		return new ResponseEntity("", header, HttpStatus.OK);
	}
}

 

Authorization: <type> <credentials>

Authorization Header 는 <type>별로 <credentials> 형식이 정해져 있는데,

Basic type 이라면 사용자이름:비밀번호 형태의 credentials 을 만든다. 

Bearer type 이라면 'Bearer ' + token 형태의 credentials 을 만든다.

jwt 토큰은 Bearer type을 사용한다.

 

여담) 토큰을 header로 담을때 token 앞에 'Bearer '를 붙이는 것이 관례인 것 같은데, 토큰을 받아서 parsing 할때 'Bearer '를 제거해야해서 그냥 빼버려도 좋을 것 같은데 관례라고 하니....

 

※ 토큰 복호화 확인은 아래 주소에서 바로 가능

  JSON Web Tokens - jwt.io

Comments