From 7dbab069e7e1628bb2e808320ebddedb55d29009 Mon Sep 17 00:00:00 2001 From: Shahbaaz Singh <37676456+ShahbaazSingh@users.noreply.github.com> Date: Wed, 15 May 2024 08:31:55 -0400 Subject: [PATCH] Updated JwtUtils to avoid 403 Forbidden error Here, we create a randomized secret key instead of the default "secret" String used before. This caused 403 errors for later versions of Spring Boot dependencies, often requiring 256 byte secret keys for generating a token. --- .../springsecurityjwt/util/JwtUtil.java | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/main/java/io/javabrains/springsecurityjwt/util/JwtUtil.java b/src/main/java/io/javabrains/springsecurityjwt/util/JwtUtil.java index ae63245..440f8a2 100644 --- a/src/main/java/io/javabrains/springsecurityjwt/util/JwtUtil.java +++ b/src/main/java/io/javabrains/springsecurityjwt/util/JwtUtil.java @@ -6,6 +6,10 @@ import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Service; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import java.security.Key; +import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -14,7 +18,27 @@ @Service public class JwtUtil { - private String SECRET_KEY = "secret"; + //Specify your algorithm here + private Key SECRET_KEY = generateKey("HmacSHA256"); + + public JwtUtil() throws NoSuchAlgorithmException { + } + + private Key generateKey(String algorithm) throws NoSuchAlgorithmException { + try { + // Initialize a KeyGenerator for the specified algorithm + KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm); + + // Generate a random secret key + SecretKey secretKey = keyGenerator.generateKey(); + + // Cast the SecretKey to the Key interface + return (Key) secretKey; + } catch (NoSuchAlgorithmException e) { + // Handle NoSuchAlgorithmException (e.g., algorithm not available) + throw new RuntimeException("Error:" + algorithm + " not available.", e); + } + } public String extractUsername(String token) { return extractClaim(token, Claims::getSubject);