forked from osopromadze/Spring-Boot-Blog-REST-API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJwtTokenProvider.java
More file actions
69 lines (57 loc) · 2.27 KB
/
JwtTokenProvider.java
File metadata and controls
69 lines (57 loc) · 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package com.sopromadze.blogapi.security;
import java.util.Date;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
@Component
public class JwtTokenProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenProvider.class);
@Value(value = "${app.jwtSecret}")
private String jwtSecret;
@Value(value = "${app.jwtExpirationInMs}")
private int jwtExpirationInMs;
public String generateToken(Authentication authentication){
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
return Jwts.builder()
.setSubject(Long.toString(userPrincipal.getId()))
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public Long getUserIdFromJWT(String token){
Claims claims = Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.getBody();
return Long.valueOf(claims.getSubject());
}
public boolean validateToken(String authToken){
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex){
LOGGER.error("Invalid JWT signature");
} catch (MalformedJwtException ex){
LOGGER.error("Invalid JWT token");
} catch (ExpiredJwtException ex){
LOGGER.error("Expired JWT token");
} catch (UnsupportedJwtException ex){
LOGGER.error("Unsupported JWT token");
} catch (IllegalArgumentException ex){
LOGGER.error("JWT claims string is empty");
}
return false;
}
}