Last active
June 8, 2024 07:30
-
-
Save sophea/3eb54878107f7712f4df8f4fb46a9e59 to your computer and use it in GitHub Desktop.
JwtTokenService.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sma.security.config; | |
import io.jsonwebtoken.Claims; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
@Component | |
public class JwtTokenService { | |
public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; | |
public static final String ROLES = "ROLES"; | |
@Value("${jwt.secret}") | |
private String secret; | |
//retrieve username from jwt token | |
public String getUsernameFromToken(String token) { | |
return getClaimFromToken(token, Claims::getSubject); | |
} | |
//retrieve expiration date from jwt token | |
public Date getExpirationDateFromToken(String token) { | |
return getClaimFromToken(token, Claims::getExpiration); | |
} | |
public List<String> getRoles(String token) { | |
return getClaimFromToken(token, claims -> (List) claims.get(ROLES)); | |
} | |
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { | |
final Claims claims = getAllClaimsFromToken(token); | |
return claimsResolver.apply(claims); | |
} | |
//for retrieving any information from token we will need the secret key | |
private Claims getAllClaimsFromToken(String token) { | |
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); | |
} | |
//check if the token has expired | |
private Boolean isTokenExpired(String token) { | |
final Date expiration = getExpirationDateFromToken(token); | |
return expiration.before(new Date()); | |
} | |
//generate token for user | |
public String generateToken(Authentication authentication) { | |
final Map<String, Object> claims = new HashMap<>(); | |
final UserDetails user = (UserDetails) authentication.getPrincipal(); | |
final List<String> roles = authentication.getAuthorities() | |
.stream() | |
.map(GrantedAuthority::getAuthority) | |
.collect(Collectors.toList()); | |
claims.put(ROLES, roles); | |
return generateToken(claims, user.getUsername()); | |
} | |
//while creating the token - | |
//1. Define claims of the token, like Issuer, Expiration, Subject, and the ID | |
//2. Sign the JWT using the HS512 algorithm and secret key. | |
//3. According to JWS Compact Serialization(https://tools.ietf.org/html/draft-ietf-jose-json-web-signature-41#section-3.1) | |
// compaction of the JWT to a URL-safe string | |
private String generateToken(Map<String, Object> claims, String subject) { | |
final long now = System.currentTimeMillis(); | |
return Jwts.builder() | |
.setClaims(claims) | |
.setSubject(subject) | |
.setIssuedAt(new Date(now)) | |
.setExpiration(new Date(now + JWT_TOKEN_VALIDITY * 1000)) | |
.signWith(SignatureAlgorithm.HS512, secret).compact(); | |
} | |
//validate token | |
public Boolean validateToken(String token) { | |
final String username = getUsernameFromToken(token); | |
return username != null && !isTokenExpired(token); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cool