Notice
Recent Posts
Recent Comments
Link
아님말고
[JWT] jwt 생성 및 검증 예제 (spring boot + gradle) 본문
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 '를 제거해야해서 그냥 빼버려도 좋을 것 같은데 관례라고 하니....
※ 토큰 복호화 확인은 아래 주소에서 바로 가능
'Java' 카테고리의 다른 글
헥사고날 아키텍처 (0) | 2023.05.11 |
---|---|
[JWT] token secret key 생성 (0) | 2023.05.10 |
[gradle] Spring Cloud Gateway Header 변경 (0) | 2023.05.08 |
[gradle] Spring Cloud Gateway 설정 및 예제 (0) | 2023.05.04 |
운영체제 줄바꿈 문자로 개행처리 하기 (0) | 2009.03.04 |
Comments