|
1 | 1 | package com.project.shopapp.components;
|
| 2 | + |
2 | 3 | import com.project.shopapp.models.User;
|
3 | 4 | import org.slf4j.Logger;
|
4 | 5 | import org.slf4j.LoggerFactory;
|
|
24 | 25 | @Component
|
25 | 26 | @RequiredArgsConstructor
|
26 | 27 | public class JwtTokenUtils {
|
27 |
| - @Value("${jwt.expiration}") |
28 |
| - private int expiration; //save to an environment variable |
29 |
| - |
30 |
| - @Value("${jwt.expiration-refresh-token}") |
31 |
| - private int expirationRefreshToken; |
| 28 | + private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class); |
| 29 | + private final TokenRepository tokenRepository; |
| 30 | + @Value("${jwt.expiration}") |
| 31 | + private int expiration; //save to an environment variable |
| 32 | + @Value("${jwt.expiration-refresh-token}") |
| 33 | + private int expirationRefreshToken; |
| 34 | + @Value("${jwt.secretKey}") |
| 35 | + private String secretKey; |
32 | 36 |
|
33 |
| - @Value("${jwt.secretKey}") |
34 |
| - private String secretKey; |
35 |
| - private static final Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class); |
36 |
| - private final TokenRepository tokenRepository; |
37 |
| - public String generateToken(com.project.shopapp.models.User user) throws Exception{ |
38 |
| - //properties => claims |
39 |
| - Map<String, Object> claims = new HashMap<>(); |
40 |
| - //this.generateSecretKey(); |
41 |
| - claims.put("phoneNumber", user.getPhoneNumber()); |
42 |
| - claims.put("userId", user.getId()); |
43 |
| - try { |
44 |
| - String token = Jwts.builder() |
45 |
| - .setClaims(claims) //how to extract claims from this ? |
46 |
| - .setSubject(user.getPhoneNumber()) |
47 |
| - .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000L)) |
48 |
| - .signWith(getSignInKey(), SignatureAlgorithm.HS256) |
49 |
| - .compact(); |
50 |
| - return token; |
51 |
| - }catch (Exception e) { |
52 |
| - //you can "inject" Logger, instead System.out.println |
53 |
| - throw new InvalidParamException("Cannot create jwt token, error: "+e.getMessage()); |
54 |
| - //return null; |
55 |
| - } |
56 |
| - } |
57 |
| - private Key getSignInKey() { |
58 |
| - byte[] bytes = Decoders.BASE64.decode(secretKey); |
59 |
| - //Keys.hmacShaKeyFor(Decoders.BASE64.decode("TaqlmGv1iEDMRiFp/pHuID1+T84IABfuA0xXh4GhiUI=")); |
60 |
| - return Keys.hmacShaKeyFor(bytes); |
61 |
| - } |
62 |
| - private String generateSecretKey() { |
63 |
| - SecureRandom random = new SecureRandom(); |
64 |
| - byte[] keyBytes = new byte[32]; // 256-bit key |
65 |
| - random.nextBytes(keyBytes); |
66 |
| - String secretKey = Encoders.BASE64.encode(keyBytes); |
67 |
| - return secretKey; |
68 |
| - } |
69 |
| - private Claims extractAllClaims(String token) { |
70 |
| - return Jwts.parserBuilder() |
71 |
| - .setSigningKey(getSignInKey()) |
72 |
| - .build() |
73 |
| - .parseClaimsJws(token) |
74 |
| - .getBody(); |
75 |
| - } |
76 |
| - public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { |
77 |
| - final Claims claims = this.extractAllClaims(token); |
78 |
| - return claimsResolver.apply(claims); |
79 |
| - } |
80 |
| - //check expiration |
81 |
| - public boolean isTokenExpired(String token) { |
82 |
| - Date expirationDate = this.extractClaim(token, Claims::getExpiration); |
83 |
| - return expirationDate.before(new Date()); |
84 |
| - } |
85 |
| - public String extractPhoneNumber(String token) { |
86 |
| - return extractClaim(token, Claims::getSubject); |
| 37 | + public String generateToken(com.project.shopapp.models.User user) throws Exception { |
| 38 | + //properties => claims |
| 39 | + Map<String, Object> claims = new HashMap<>(); |
| 40 | + //this.generateSecretKey(); |
| 41 | + claims.put("phoneNumber", user.getPhoneNumber()); |
| 42 | + claims.put("userId", user.getId()); |
| 43 | + try { |
| 44 | + String token = Jwts.builder() |
| 45 | + .setClaims(claims) //how to extract claims from this ? |
| 46 | + .setSubject(user.getPhoneNumber()) |
| 47 | + .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000L)) |
| 48 | + .signWith(getSignInKey(), SignatureAlgorithm.HS256) |
| 49 | + .compact(); |
| 50 | + return token; |
| 51 | + } catch (Exception e) { |
| 52 | + //you can "inject" Logger, instead System.out.println |
| 53 | + throw new InvalidParamException("Cannot create jwt token, error: " + e.getMessage()); |
| 54 | + //return null; |
87 | 55 | }
|
88 |
| - public boolean validateToken(String token, User userDetails) { |
89 |
| - try { |
90 |
| - String phoneNumber = extractPhoneNumber(token); |
91 |
| - Token existingToken = tokenRepository.findByToken(token); |
92 |
| - if(existingToken == null || |
93 |
| - existingToken.isRevoked() == true || |
94 |
| - !userDetails.isActive() |
95 |
| - ) { |
96 |
| - return false; |
97 |
| - } |
98 |
| - return (phoneNumber.equals(userDetails.getUsername())) |
99 |
| - && !isTokenExpired(token); |
100 |
| - } catch (MalformedJwtException e) { |
101 |
| - logger.error("Invalid JWT token: {}", e.getMessage()); |
102 |
| - } catch (ExpiredJwtException e) { |
103 |
| - logger.error("JWT token is expired: {}", e.getMessage()); |
104 |
| - } catch (UnsupportedJwtException e) { |
105 |
| - logger.error("JWT token is unsupported: {}", e.getMessage()); |
106 |
| - } catch (IllegalArgumentException e) { |
107 |
| - logger.error("JWT claims string is empty: {}", e.getMessage()); |
108 |
| - } |
| 56 | + } |
109 | 57 |
|
| 58 | + private Key getSignInKey() { |
| 59 | + byte[] bytes = Decoders.BASE64.decode(secretKey); |
| 60 | + //Keys.hmacShaKeyFor(Decoders.BASE64.decode("TaqlmGv1iEDMRiFp/pHuID1+T84IABfuA0xXh4GhiUI=")); |
| 61 | + return Keys.hmacShaKeyFor(bytes); |
| 62 | + } |
| 63 | + |
| 64 | + private String generateSecretKey() { |
| 65 | + SecureRandom random = new SecureRandom(); |
| 66 | + byte[] keyBytes = new byte[32]; // 256-bit key |
| 67 | + random.nextBytes(keyBytes); |
| 68 | + String secretKey = Encoders.BASE64.encode(keyBytes); |
| 69 | + return secretKey; |
| 70 | + } |
| 71 | + |
| 72 | + private Claims extractAllClaims(String token) { |
| 73 | + return Jwts.parserBuilder() |
| 74 | + .setSigningKey(getSignInKey()) |
| 75 | + .build() |
| 76 | + .parseClaimsJws(token) |
| 77 | + .getBody(); |
| 78 | + } |
| 79 | + |
| 80 | + public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { |
| 81 | + final Claims claims = this.extractAllClaims(token); |
| 82 | + return claimsResolver.apply(claims); |
| 83 | + } |
| 84 | + |
| 85 | + //check expiration |
| 86 | + public boolean isTokenExpired(String token) { |
| 87 | + Date expirationDate = this.extractClaim(token, Claims::getExpiration); |
| 88 | + return expirationDate.before(new Date()); |
| 89 | + } |
| 90 | + |
| 91 | + public String extractPhoneNumber(String token) { |
| 92 | + return extractClaim(token, Claims::getSubject); |
| 93 | + } |
| 94 | + |
| 95 | + public boolean validateToken(String token, User userDetails) { |
| 96 | + try { |
| 97 | + String phoneNumber = extractPhoneNumber(token); |
| 98 | + Token existingToken = tokenRepository.findByToken(token); |
| 99 | + if (existingToken == null || |
| 100 | + existingToken.isRevoked() || |
| 101 | + !userDetails.isActive() |
| 102 | + ) { |
110 | 103 | return false;
|
| 104 | + } |
| 105 | + return (phoneNumber.equals(userDetails.getUsername())) |
| 106 | + && !isTokenExpired(token); |
| 107 | + } catch (MalformedJwtException e) { |
| 108 | + logger.error("Invalid JWT token: {}", e.getMessage()); |
| 109 | + } catch (ExpiredJwtException e) { |
| 110 | + logger.error("JWT token is expired: {}", e.getMessage()); |
| 111 | + } catch (UnsupportedJwtException e) { |
| 112 | + logger.error("JWT token is unsupported: {}", e.getMessage()); |
| 113 | + } catch (IllegalArgumentException e) { |
| 114 | + logger.error("JWT claims string is empty: {}", e.getMessage()); |
111 | 115 | }
|
| 116 | + |
| 117 | + return false; |
| 118 | + } |
112 | 119 | }
|
0 commit comments