Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated JwtUtils to avoid 403 Forbidden error #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion src/main/java/io/javabrains/springsecurityjwt/util/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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);
Expand Down