|
1 | 1 | package com.yourssu.roomescape.util; |
2 | 2 |
|
3 | 3 | import com.yourssu.roomescape.config.JwtProperties; |
| 4 | +import com.yourssu.roomescape.exception.ErrorCode; |
| 5 | +import com.yourssu.roomescape.exception.UnauthenticatedException; |
4 | 6 | import 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; |
6 | 13 | import io.jsonwebtoken.security.Keys; |
7 | 14 | import org.springframework.stereotype.Component; |
8 | 15 |
|
| 16 | +import javax.crypto.SecretKey; |
9 | 17 | import java.security.Key; |
10 | 18 | import java.util.Date; |
11 | 19 |
|
@@ -35,18 +43,32 @@ public String createToken(Member member) { |
35 | 43 | } |
36 | 44 |
|
37 | 45 | public String getEmail(String token) { |
38 | | - return getClaims(token).getSubject(); |
| 46 | + return parseClaims(token).getSubject(); |
39 | 47 | } |
40 | 48 |
|
41 | 49 | public String getRole(String token) { |
42 | | - return getClaims(token).get("role", String.class); |
| 50 | + return parseClaims(token).get("role", String.class); |
43 | 51 | } |
44 | 52 |
|
45 | | - private Claims getClaims(String token) { |
46 | | - return Jwts.parser() |
47 | | - .setSigningKey(key) |
48 | | - .build() |
49 | | - .parseSignedClaims(token) |
50 | | - .getPayload(); |
| 53 | + private Claims parseClaims(String token) { |
| 54 | + if (token == null || token.isBlank()) { |
| 55 | + throw new UnauthenticatedException(ErrorCode.TOKEN_NOT_FOUND); |
| 56 | + } |
| 57 | + |
| 58 | + try { |
| 59 | + return Jwts.parser() |
| 60 | + .verifyWith((SecretKey) key) |
| 61 | + .build() |
| 62 | + .parseSignedClaims(token) |
| 63 | + .getPayload(); |
| 64 | + } catch (ExpiredJwtException e) { |
| 65 | + throw new UnauthenticatedException(ErrorCode.EXPIRED_TOKEN); |
| 66 | + } catch (UnsupportedJwtException e) { |
| 67 | + throw new UnauthenticatedException(ErrorCode.UNSUPPORTED_TOKEN); |
| 68 | + } catch (MalformedJwtException e) { |
| 69 | + throw new UnauthenticatedException(ErrorCode.MALFORMED_TOKEN); |
| 70 | + } catch (SignatureException | IllegalArgumentException e) { |
| 71 | + throw new UnauthenticatedException(ErrorCode.INVALID_TOKEN); |
| 72 | + } |
51 | 73 | } |
52 | 74 | } |
0 commit comments