11package com .yourssu .roomescape .util ;
22
33import com .yourssu .roomescape .config .JwtProperties ;
4+ import com .yourssu .roomescape .exception .ErrorCode ;
5+ import com .yourssu .roomescape .exception .UnauthenticatedException ;
46import com .yourssu .roomescape .member .Member ;
5- import io .jsonwebtoken .*;
7+ import io .jsonwebtoken .Claims ;
8+ import io .jsonwebtoken .ExpiredJwtException ;
9+ import io .jsonwebtoken .Jwts ;
10+ import io .jsonwebtoken .MalformedJwtException ;
11+ import io .jsonwebtoken .UnsupportedJwtException ;
12+ import io .jsonwebtoken .security .SignatureException ;
613import io .jsonwebtoken .security .Keys ;
714import org .springframework .stereotype .Component ;
815
16+ import javax .crypto .SecretKey ;
917import java .security .Key ;
1018import java .util .Date ;
1119
@@ -35,11 +43,11 @@ public String createToken(Member member) {
3543 }
3644
3745 public String getEmail (String token ) {
38- return getClaims (token ).getSubject ();
46+ return parseClaims (token ).getSubject ();
3947 }
4048
4149 public String getRole (String token ) {
42- return getClaims (token ).get ("role" , String .class );
50+ return parseClaims (token ).get ("role" , String .class );
4351 }
4452
4553 private Claims getClaims (String token ) {
@@ -48,5 +56,25 @@ private Claims getClaims(String token) {
4856 .build ()
4957 .parseSignedClaims (token )
5058 .getPayload ();
59+ private Claims parseClaims (String token ) {
60+ if (token == null || token .isBlank ()) {
61+ throw new UnauthenticatedException (ErrorCode .TOKEN_NOT_FOUND );
62+ }
63+
64+ try {
65+ return Jwts .parser ()
66+ .verifyWith ((SecretKey ) key )
67+ .build ()
68+ .parseSignedClaims (token )
69+ .getPayload ();
70+ } catch (ExpiredJwtException e ) {
71+ throw new UnauthenticatedException (ErrorCode .EXPIRED_TOKEN );
72+ } catch (UnsupportedJwtException e ) {
73+ throw new UnauthenticatedException (ErrorCode .UNSUPPORTED_TOKEN );
74+ } catch (MalformedJwtException e ) {
75+ throw new UnauthenticatedException (ErrorCode .MALFORMED_TOKEN );
76+ } catch (SignatureException | IllegalArgumentException e ) {
77+ throw new UnauthenticatedException (ErrorCode .INVALID_TOKEN );
78+ }
5179 }
5280}
0 commit comments