|
| 1 | +package com.biancodavide3.jwt; |
| 2 | + |
| 3 | +import io.jsonwebtoken.Claims; |
| 4 | +import io.jsonwebtoken.Jwts; |
| 5 | +import io.jsonwebtoken.SignatureAlgorithm; |
| 6 | +import io.jsonwebtoken.io.Decoders; |
| 7 | +import io.jsonwebtoken.security.Keys; |
| 8 | +import org.springframework.stereotype.Service; |
| 9 | + |
| 10 | +import java.security.Key; |
| 11 | +import java.util.Date; |
| 12 | +import java.util.HashMap; |
| 13 | +import java.util.Map; |
| 14 | +import java.util.function.Function; |
| 15 | + |
| 16 | +@Service |
| 17 | +public class GenericTokenService { |
| 18 | + |
| 19 | + // todo make this come from vault |
| 20 | + private String secretKey; |
| 21 | + |
| 22 | + // creation |
| 23 | + |
| 24 | + protected String generateToken( |
| 25 | + String subject, |
| 26 | + int expiration, |
| 27 | + Map<String, Object> extraClaims |
| 28 | + ) { |
| 29 | + return Jwts |
| 30 | + .builder() |
| 31 | + .setClaims(extraClaims) |
| 32 | + .setSubject(subject) |
| 33 | + .setIssuedAt(new Date(System.currentTimeMillis())) |
| 34 | + .setExpiration(new Date(System.currentTimeMillis() + hoursToMillis(expiration))) |
| 35 | + .signWith(signingKey(), SignatureAlgorithm.HS256) |
| 36 | + .compact(); |
| 37 | + } |
| 38 | + |
| 39 | + protected String generateToken(String subject, int expiration) { |
| 40 | + return generateToken(subject, expiration, new HashMap<>()); |
| 41 | + } |
| 42 | + |
| 43 | + private long hoursToMillis(int expiration) { |
| 44 | + return expiration * 60L * 60L * 1000L; |
| 45 | + } |
| 46 | + |
| 47 | + private Key signingKey() { |
| 48 | + byte[] bytes = Decoders.BASE64.decode(secretKey); |
| 49 | + return Keys.hmacShaKeyFor(bytes); |
| 50 | + } |
| 51 | + |
| 52 | + // validation |
| 53 | + |
| 54 | + protected <T> T extractClaim(String token, Function<Claims, T> claimsResolver) { |
| 55 | + Claims claims = Jwts |
| 56 | + .parserBuilder() |
| 57 | + .setSigningKey(signingKey()) |
| 58 | + .build() |
| 59 | + .parseClaimsJws(token) |
| 60 | + .getBody(); |
| 61 | + return claimsResolver.apply(claims); |
| 62 | + } |
| 63 | + |
| 64 | + protected boolean isTokenValid(String token, String subject) { |
| 65 | + String extractedSubject = extractClaim(token, Claims::getSubject); |
| 66 | + return extractedSubject.equals(subject) && !isTokenExpired(token); |
| 67 | + } |
| 68 | + |
| 69 | + private boolean isTokenExpired(String token) { |
| 70 | + Date extractedDate = extractClaim(token, Claims::getExpiration); |
| 71 | + return extractedDate.before(new Date()); |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments