Hi there! check out my previous blog How Keys.hmacShaKeyFor() works ? It will you brief idea.
Find other JWT blogs within label JWT (https://nurturedknowledge.blogspot.com/search/label/JWT?&max-results=9)
Also check it out this blog which uses Keys.secretKeyFor() method to generate security.
Here is the link: JWT tokens in Java using the jjwt-api version 0.11.5 in Eclipse
Let's write program to use a user-defined security key and then use it with Keys.hmacShaKeyFor().
package jwtdemo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;
public class JwtUtil1{
// User-defined secret key (should be stored securely in a real application)
private static final String USER_SECRET = "your-secret-key-here-replace-me";
// Encode the user-defined secret key in Base64
private static final String BASE64_SECRET = Base64.getEncoder().encodeToString(USER_SECRET.getBytes());
// Generate the signing key from the Base64 encoded secret
private static final Key SIGNING_KEY = Keys.hmacShaKeyFor(Base64.getDecoder().decode(BASE64_SECRET));
// Method to generate a JWT token
public static String generateToken(String subject) {
Date now = new Date();
Date expiryDate = new Date(now.getTime() + 3600000); // Token expires in 1 hour
return Jwts.builder()
.setId(UUID.randomUUID().toString()) // Unique identifier for the token
.setSubject(subject) // Who the token is for
.setIssuedAt(now) // When the token was issued
.setExpiration(expiryDate) // When the token expires
.signWith(SIGNING_KEY) // Sign the token with our derived signing key
.compact(); // Serialize the claims and generate the JWT
}
// Method to parse and validate a JWT token
public static Claims parseAndValidateToken(String token) {
try {
return Jwts.parserBuilder()
.setSigningKey(SIGNING_KEY) // Use the same signing key for validation
.build()
.parseClaimsJws(token) // Parse the token and verify the signature
.getBody(); // Get the claims from the parsed token
} catch (Exception e) {
// Token is invalid or has expired
return null;
}
}
public static void main(String[] args) {
// Example usage:
// 1. Generate a token for a user
String username = "anotherUser";
String token = generateToken(username);
System.out.println("Generated Token (using user-defined key): " + token);
// 2. Parse and validate the token
Claims claims = parseAndValidateToken(token);
if (claims != null) {
System.out.println("\n JWTUtil-1 is called");
System.out.println("\nToken is valid!");
System.out.println("Subject: " + claims.getSubject());
System.out.println("Issued At: " + claims.getIssuedAt());
System.out.println("Expiration: " + claims.getExpiration());
System.out.println("Token ID: " + claims.getId());
} else {
System.out.println("\nToken is invalid or has expired.");
}
// 3. Try to parse a token generated with a different (default) key
Key defaultKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
String tokenWithDefaultKey = Jwts.builder()
.setSubject("test")
.signWith(defaultKey)
.compact();
Claims claimsFromDefaultKey = parseAndValidateToken(tokenWithDefaultKey);
if (claimsFromDefaultKey == null) {
System.out.println("\nToken generated with a different key is correctly identified as invalid.");
} else {
System.out.println("\nToken generated with a different key was surprisingly valid!");
}
}
}
0 Comments