forked from NeilAlishev/SpringCourse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJWTUtil.java
More file actions
44 lines (36 loc) · 1.36 KB
/
JWTUtil.java
File metadata and controls
44 lines (36 loc) · 1.36 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
package ru.alishev.springcourse.FirstSecurityApp.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.ZonedDateTime;
import java.util.Date;
/**
* @author Neil Alishev
*/
@Component
public class JWTUtil {
@Value("${jwt_secret}")
private String secret;
public String generateToken(String username) {
Date expirationDate = Date.from(ZonedDateTime.now().plusMinutes(60).toInstant());
return JWT.create()
.withSubject("User details")
.withClaim("username", username)
.withIssuedAt(new Date())
.withIssuer("alishev")
.withExpiresAt(expirationDate)
.sign(Algorithm.HMAC256(secret));
}
public String validateTokenAndRetrieveClaim(String token) throws JWTVerificationException {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret))
.withSubject("User details")
.withIssuer("alishev")
.build();
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("username").asString();
}
}