| 1 | package com.tecmilenio.mapsconect.security; |
| 2 | |
| 3 | import io.jsonwebtoken.Claims; |
| 4 | import io.jsonwebtoken.Jwts; |
| 5 | import io.jsonwebtoken.SignatureAlgorithm; |
| 6 | import io.jsonwebtoken.security.Keys; |
| 7 | import org.springframework.beans.factory.annotation.Value; |
| 8 | import org.springframework.security.core.userdetails.UserDetails; |
| 9 | import org.springframework.stereotype.Component; |
| 10 | |
| 11 | import javax.crypto.SecretKey; |
| 12 | import java.util.Date; |
| 13 | import java.util.HashMap; |
| 14 | import java.util.Map; |
| 15 | |
| 16 | @Component |
| 17 | public class JwtTokenProvider { |
| 18 | |
| 19 | @Value("${jwt.secret}") |
| 20 | private String jwtSecret; |
| 21 | |
| 22 | @Value("${jwt.expiration}") |
| 23 | private long jwtExpirationMs; |
| 24 | |
| 25 | private SecretKey getSigningKey() { |
| 26 | return Keys.hmacShaKeyFor(jwtSecret.getBytes()); |
| 27 | } |
| 28 | |
| 29 | public String generateToken(String username) { |
| 30 | Map<String, Object> claims = new HashMap<>(); |
| 31 | return createToken(claims, username); |
| 32 | } |
| 33 | |
| 34 | public String generateTokenWithClaims(String username, Map<String, Object> claims) { |
| 35 | return createToken(claims, username); |
| 36 | } |
| 37 | |
| 38 | private String createToken(Map<String, Object> claims, String subject) { |
| 39 | Date now = new Date(); |
| 40 | Date expiryDate = new Date(now.getTime() + jwtExpirationMs); |
| 41 | |
| 42 | return Jwts.builder() |
| 43 | .setClaims(claims) |
| 44 | .setSubject(subject) |
| 45 | .setIssuedAt(now) |
| 46 | .setExpiration(expiryDate) |
| 47 | .signWith(getSigningKey(), SignatureAlgorithm.HS512) |
| 48 | .compact(); |
| 49 | } |
| 50 | |
| 51 | public String getUsernameFromToken(String token) { |
| 52 | return getClaimsFromToken(token).getSubject(); |
| 53 | } |
| 54 | |
| 55 | public boolean validateToken(String token) { |
| 56 | try { |
| 57 | Jwts.parser() |
| 58 | .verifyWith(getSigningKey()) |
| 59 | .build() |
| 60 | .parseSignedClaims(token); |
| 61 | return true; |
| 62 | } catch (Exception e) { |
| 63 | return false; |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | private Claims getClaimsFromToken(String token) { |
| 68 | return Jwts.parser() |
| 69 | .verifyWith(getSigningKey()) |
| 70 | .build() |
| 71 | .parseSignedClaims(token) |
| 72 | .getPayload(); |
| 73 | } |
| 74 | } |