Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
@Service
public class JWTUtils {
/**
* Based the secret key it is doing the signing
*/
private String secret = "learnitcodeit";
/**
* Extracting username from the token
* @param token
* @return
*/
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
/**
* Extracting the expiry of the token
* @param token
* @return
*/
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
/**
* Extracting the claim based on the condition
* @param <T>
* @param token
* @param claimsResolver
* @return
*/
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
private Boolean isTokenExpired(String token) {
return extractExpiration(token).before(new Date());
}
/**
* Generating token
* @param username
* @return
*/
public String generateToken(String username) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, username);
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10))
.signWith(SignatureAlgorithm.HS256, secret).compact();
}
/**
* Validating the token
* @param token
* @param userDetails
* @return
*/
public Boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment