1 | package finki.diplomska.tripplanner.security;
|
---|
2 |
|
---|
3 | import finki.diplomska.tripplanner.models.User;
|
---|
4 | import io.jsonwebtoken.*;
|
---|
5 | import org.springframework.security.core.Authentication;
|
---|
6 | import org.springframework.stereotype.Component;
|
---|
7 |
|
---|
8 | import java.util.Date;
|
---|
9 | import java.util.HashMap;
|
---|
10 | import java.util.Map;
|
---|
11 |
|
---|
12 | @Component
|
---|
13 | public class JwtTokenProvider {
|
---|
14 | //Generate the token
|
---|
15 |
|
---|
16 | public String generateToken(Authentication authentication){
|
---|
17 | User user = (User)authentication.getPrincipal();
|
---|
18 | Date now = new Date(System.currentTimeMillis());
|
---|
19 |
|
---|
20 | Date expiryDate = new Date(now.getTime()+SecurityConstants.EXPIRATION_TIME);
|
---|
21 |
|
---|
22 | String userId = Long.toString(user.getId());
|
---|
23 |
|
---|
24 | Map<String,Object> claims = new HashMap<>();
|
---|
25 | claims.put("id", (Long.toString(user.getId())));
|
---|
26 | claims.put("username", user.getUsername());
|
---|
27 | claims.put("fullName", user.getFullName());
|
---|
28 |
|
---|
29 | return Jwts.builder()
|
---|
30 | .setSubject(userId)
|
---|
31 | .setClaims(claims)
|
---|
32 | .setIssuedAt(now)
|
---|
33 | .setExpiration(expiryDate)
|
---|
34 | .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET)
|
---|
35 | .compact();
|
---|
36 | }
|
---|
37 |
|
---|
38 | //Validate the token
|
---|
39 | public boolean validateToken(String token){
|
---|
40 | try{
|
---|
41 | Jwts.parser().setSigningKey(SecurityConstants.SECRET).parseClaimsJws(token);
|
---|
42 | return true;
|
---|
43 | }catch (SignatureException ex){
|
---|
44 | System.out.println("Invalid JWT Signature");
|
---|
45 | }catch (MalformedJwtException ex){
|
---|
46 | System.out.println("Invalid JWT Token");
|
---|
47 | }catch (ExpiredJwtException ex){
|
---|
48 | System.out.println("Expired JWT token");
|
---|
49 | }catch (UnsupportedJwtException ex){
|
---|
50 | System.out.println("Unsupported JWT token");
|
---|
51 | }catch (IllegalArgumentException ex){
|
---|
52 | System.out.println("JWT claims string is empty");
|
---|
53 | }
|
---|
54 | return false;
|
---|
55 | }
|
---|
56 | //Get user Id from token
|
---|
57 | public Long getUserIdFromJWT(String token){
|
---|
58 | Claims claims = Jwts.parser().setSigningKey(SecurityConstants.SECRET).parseClaimsJws(token).getBody();
|
---|
59 | String id = (String)claims.get("id");
|
---|
60 |
|
---|
61 | return Long.parseLong(id);
|
---|
62 | }
|
---|
63 | }
|
---|