diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/jwtsignkey/jwtconfig/JwtUtils.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/jwtsignkey/jwtconfig/JwtUtils.java index 7ee397481b..5fbd4c6de3 100644 --- a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/jwtsignkey/jwtconfig/JwtUtils.java +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/jwtsignkey/jwtconfig/JwtUtils.java @@ -16,8 +16,6 @@ import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import javax.crypto.SecretKey; -import java.nio.charset.StandardCharsets; -import java.security.Key; import java.util.Date; @Component @@ -30,8 +28,6 @@ public class JwtUtils { @Value("${baeldung.app.jwtExpirationMs}") private int jwtExpirationMs; - SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(jwtSecret)); - public String generateJwtToken(Authentication authentication) { UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal(); @@ -40,19 +36,19 @@ public class JwtUtils { .subject((userPrincipal.getUsername())) .issuedAt(new Date()) .expiration(new Date((new Date()).getTime() + jwtExpirationMs)) - .signWith(key) + .signWith(getSigningKey()) .compact(); } - private Key getSigningKey() { - byte[] keyBytes = this.jwtSecret.getBytes(StandardCharsets.UTF_8); + private SecretKey getSigningKey() { + byte[] keyBytes = Decoders.BASE64.decode(jwtSecret); return Keys.hmacShaKeyFor(keyBytes); } public String getUserNameFromJwtToken(String token) { return Jwts.parser() - .verifyWith(key) + .verifyWith(getSigningKey()) .build() .parseSignedClaims(token) .getPayload() @@ -63,7 +59,7 @@ public class JwtUtils { public boolean validateJwtToken(String authToken) { try { Jwts.parser() - . verifyWith(key) + .verifyWith(getSigningKey()) .build() .parseSignedClaims(authToken); return true;