source: trip-planner/src/main/java/finki/diplomska/tripplanner/security/JwtTokenProvider.java

Last change on this file was 84d0fbb, checked in by Ema <ema_spirova@…>, 3 years ago

spring security 2.0

  • Property mode set to 100644
File size: 2.2 KB
Line 
1package finki.diplomska.tripplanner.security;
2
3import finki.diplomska.tripplanner.models.User;
4import io.jsonwebtoken.*;
5import org.springframework.security.core.Authentication;
6import org.springframework.stereotype.Component;
7
8import java.util.Date;
9import java.util.HashMap;
10import java.util.Map;
11
12@Component
13public 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}
Note: See TracBrowser for help on using the repository browser.