1616import org .springframework .stereotype .Component ;
1717
1818import javax .crypto .SecretKey ;
19- import java .nio .charset .StandardCharsets ;
20- import java .security .Key ;
2119import java .util .Date ;
2220
2321@ Component
@@ -30,8 +28,6 @@ public class JwtUtils {
3028 @ Value ("${baeldung.app.jwtExpirationMs}" )
3129 private int jwtExpirationMs ;
3230
33- SecretKey key = Keys .hmacShaKeyFor (Decoders .BASE64 .decode (jwtSecret ));
34-
3531 public String generateJwtToken (Authentication authentication ) {
3632
3733 UserDetailsImpl userPrincipal = (UserDetailsImpl ) authentication .getPrincipal ();
@@ -40,19 +36,19 @@ public String generateJwtToken(Authentication authentication) {
4036 .subject ((userPrincipal .getUsername ()))
4137 .issuedAt (new Date ())
4238 .expiration (new Date ((new Date ()).getTime () + jwtExpirationMs ))
43- .signWith (key )
39+ .signWith (getSigningKey () )
4440 .compact ();
4541
4642 }
4743
48- private Key getSigningKey () {
49- byte [] keyBytes = this . jwtSecret . getBytes ( StandardCharsets . UTF_8 );
44+ private SecretKey getSigningKey () {
45+ byte [] keyBytes = Decoders . BASE64 . decode ( jwtSecret );
5046 return Keys .hmacShaKeyFor (keyBytes );
5147 }
5248
5349 public String getUserNameFromJwtToken (String token ) {
5450 return Jwts .parser ()
55- .verifyWith (key )
51+ .verifyWith (getSigningKey () )
5652 .build ()
5753 .parseSignedClaims (token )
5854 .getPayload ()
@@ -63,7 +59,7 @@ public String getUserNameFromJwtToken(String token) {
6359 public boolean validateJwtToken (String authToken ) {
6460 try {
6561 Jwts .parser ()
66- . verifyWith (key )
62+ .verifyWith (getSigningKey () )
6763 .build ()
6864 .parseSignedClaims (authToken );
6965 return true ;
0 commit comments