Created
January 16, 2022 14:48
-
-
Save iamprafful/5e3f0bfd93cdb07707681f0175b7eb68 to your computer and use it in GitHub Desktop.
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.example.api.util; | |
import io.jsonwebtoken.Claims; | |
import io.jsonwebtoken.Jwts; | |
import io.jsonwebtoken.SignatureAlgorithm; | |
import io.jsonwebtoken.security.Keys; | |
import org.springframework.security.core.userdetails.UserDetails; | |
import org.springframework.stereotype.Component; | |
import java.io.Serializable; | |
import java.security.Key; | |
import java.util.Date; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.function.Function; | |
@Component | |
public class JwtTokenUtil implements Serializable { | |
public static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; | |
Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256); | |
public String getUsernameFromToken(String token) { | |
return getClaimFromToken(token, Claims::getSubject); | |
} | |
public Date getExpirationDateFromToken(String token) { | |
return getClaimFromToken(token, Claims::getExpiration); | |
} | |
public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { | |
final Claims claims = getAllClaimsFromToken(token); | |
return claimsResolver.apply(claims); | |
} | |
private Claims getAllClaimsFromToken(String token) { | |
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody(); | |
} | |
private Boolean isTokenExpired(String token) { | |
final Date expiration = getExpirationDateFromToken(token); | |
return expiration.before(new Date()); | |
} | |
public String generateToken(UserDetails userDetails) { | |
Map<String, Object> claims = new HashMap<>(); | |
return Jwts.builder().setClaims(claims).setSubject(userDetails.getUsername()).setIssuedAt(new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000)).signWith(key).compact(); | |
} | |
public Boolean validateToken(String token, UserDetails userDetails) { | |
final String username = getUsernameFromToken(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