73 lines
2.3 KiB
Java
73 lines
2.3 KiB
Java
package zw.qantra.tm.utils;
|
|
|
|
import io.jsonwebtoken.*;
|
|
import io.jsonwebtoken.security.Keys;
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
import org.springframework.security.core.userdetails.UserDetails;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import javax.crypto.SecretKey;
|
|
import java.util.Date;
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.function.Function;
|
|
|
|
@Component
|
|
public class JwtUtils {
|
|
|
|
@Value("${jwt.secret:defaultSecretKey123456789012345678901234567890}")
|
|
private String secret;
|
|
|
|
@Value("${jwt.expiration:86400000}")
|
|
private Long expiration;
|
|
|
|
private SecretKey getSigningKey() {
|
|
return Keys.hmacShaKeyFor(secret.getBytes());
|
|
}
|
|
|
|
public String extractUsername(String token) {
|
|
return extractClaim(token, Claims::getSubject);
|
|
}
|
|
|
|
public Date extractExpiration(String token) {
|
|
return extractClaim(token, Claims::getExpiration);
|
|
}
|
|
|
|
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()
|
|
.verifyWith(getSigningKey())
|
|
.build()
|
|
.parseSignedClaims(token)
|
|
.getPayload();
|
|
}
|
|
|
|
private Boolean isTokenExpired(String token) {
|
|
return extractExpiration(token).before(new Date());
|
|
}
|
|
|
|
public String generateToken(UserDetails userDetails) {
|
|
Map<String, Object> claims = new HashMap<>();
|
|
return createToken(claims, userDetails.getUsername());
|
|
}
|
|
|
|
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() + expiration))
|
|
.signWith(getSigningKey(), SignatureAlgorithm.HS256)
|
|
.compact();
|
|
}
|
|
|
|
public Boolean validateToken(String token, UserDetails userDetails) {
|
|
final String username = extractUsername(token);
|
|
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
|
|
}
|
|
}
|