Creating a Spring Security Key for Signing a JWT Token

This commit is contained in:
michaelin007 2024-03-12 11:44:53 +00:00
parent 89963eefd7
commit 9e46a49f20

View File

@ -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;