허원철의 개발 블로그

auth0 JWT 활용하기 본문

authentication

auth0 JWT 활용하기

허원철 2017. 2. 12. 15:58

이번 글은 auth0에서 제공하는 jwt를 활용하는 글입니다. 

※ jwt에 대해 모르시거나 이해가 부족하시다면, 간략한 글이지만 이전 포스팅을 읽어보시면 미약하게(?) 도움이 되시리라 생각합니다...(http://heowc.tistory.com/20)



JWT 생성


- 기본적으로는 create(), sign() 메소드만 있으면 됩니다. 그 안에 부가적인 정보를 추가하기 위해 claims를 추가 할 수도 있고 많이 쓰이는 내용은 별개로 추가할 수 있도록 되어 있습니다. (withExpiresAt, withIssuerAt, ... 등등)


1
2
3
4
5
6
7
8
9
10
11
EXPIRES_DATE  = Date.from(EXPIRES_LOCAL.toInstant(ZoneOffset.ofHours(9)));
    
try {
    JWT_TOKEN = JWT.create()
                    .withIssuer("wonchul")
                    .withExpiresAt(EXPIRES_DATE) // 만료일
                    .sign(Algorithm.HMAC256(JWT_SECRECT_KEY));
catch (JWTCreationException createEx) {
    System.out.println("Create Error");
    createEx.printStackTrace();
}
cs


- 생성을 실패한다면, JWTCreationException이 발생합니다.

- sign에서는 다양한 알고리즘을 제공합니다.


JWSAlgorithmDescription
HS256HMAC256HMAC with SHA-256
HS384HMAC384HMAC with SHA-384
HS512HMAC512HMAC with SHA-512
RS256RSA256RSASSA-PKCS1-v1_5 with SHA-256
RS384RSA384RSASSA-PKCS1-v1_5 with SHA-384
RS512RSA512RSASSA-PKCS1-v1_5 with SHA-512
ES256ECDSA256ECDSA with curve P-256 and SHA-256
ES384ECDSA384ECDSA with curve P-384 and SHA-384
ES512ECDSA512ECDSA with curve P-521 and SHA-512

<출처 : https://github.com/auth0/java-jwt >



JWT 변환


- jwt를 변환하는 메소드를 제공합니다.


1
2
3
4
5
6
try {
    JWT.decode(JWT_TOKEN);
catch (JWTDecodeException decodeEx) {
    System.out.println("Decode Error");
    decodeEx.printStackTrace();
}
cs


- 변환이 실패하면, JWTDecodeException이 발생합니다.

- decode()를 하면 JWT객체롤 반환됩니다. JWT객체에서는 생성될 때의 데이터 정보를 획득할 수 있습니다.



JWT 검증


- jwt를 검증할 수 있는 메소드입니다. (내부적으로 decode도 같이 합니다.)

- 날짜, 알고리즘, Claims 검증을 합니다.


1
2
3
4
5
6
7
8
9
10
11
try {
    JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWT_SECRECT_KEY))
                                .withIssuer("wonchul")
                                .acceptExpiresAt(DAY * 4// 만료일 -4일
                                .build();
            
    DecodedJWT jwt = verifier.verify(JWT_TOKEN);
catch (JWTVerificationException verificationEx) {
    System.out.println("Verify Error");
    verificationEx.printStackTrace();
}
cs


- 검증이 실패하면(decode가 실패하거나.. 토큰이 만료되었거나.. 등등), JWTVerificationException이 발생합니다.

- decode()와 같이 DecodedJWT 에는 JWT객체가 있으므로, 생성될 때의 데이터 정보를 획득할 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
System.out.println("=================== test_verifyJwtToken ===================");
System.out.println("jwt token         : " + jwt.getToken());
System.out.println("jwt algorithm     : " + jwt.getAlgorithm());
System.out.println("jwt claims        : " + jwt.getClaims());
System.out.println("jwt issuer        : " + jwt.getIssuer());
System.out.println("jwt issuer date   : " + jwt.getIssuedAt());
System.out.println("jwt expires date  : " + jwt.getExpiresAt());
System.out.println("jwt signature     : " + jwt.getSignature());
System.out.println("jwt type          : " + jwt.getType());
System.out.println("jwt key id        : " + jwt.getKeyId());
System.out.println("jwt id            : " + jwt.getId());
System.out.println("jwt subject       : " + jwt.getSubject());
System.out.println("jwt content type  : " + jwt.getContentType());
System.out.println("jwt audience list : " + jwt.getAudience());
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
=================== test_verifyJwtToken ===================
jwt token         : eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ3b25jaHVsIiwiZXhwIjoxNDg2ODI1MjAwfQ.j7xrHVu6t_MSe6xjPsMA9Gd9f2TONX4X6Dc1XjaFm9o
jwt algorithm     : HS256
jwt claims        : {iss=com.auth0.jwt.impl.JsonNodeClaim@145a821d, exp=com.auth0.jwt.impl.JsonNodeClaim@6caa4dc5}
jwt issuer        : wonchul
jwt issuer date   : null
jwt expires date  : Sun Feb 12 00:00:00 KST 2017
jwt signature     : j7xrHVu6t_MSe6xjPsMA9Gd9f2TONX4X6Dc1XjaFm9o
jwt type          : null
jwt key id        : null
jwt id            : null
jwt subject       : null
jwt content type  : null
jwt audience list : null
cs



참고


- 이번 글은 spring boot + security + jwt 를 작성하기 전에 간단히 내용 정리 겸 작성한 포스팅입니다.(내용이 많이 부실합니다..) 코드는 깃헙 자료를 보시고 참고 하시면 되겠습니다. (SpringBootSecurityJwt - test)

https://github.com/auth0/java-jwt

'authentication' 카테고리의 다른 글

OAuth ...? JWT...!  (440) 2016.12.05
Comments