-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTokenService.java
More file actions
49 lines (41 loc) · 1.46 KB
/
Copy pathTokenService.java
File metadata and controls
49 lines (41 loc) · 1.46 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
package application.service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import org.springframework.stereotype.Service;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import application.model.Usuario;
@Service
public class TokenService {
private String tokenKey = "123456789";
private Instant expirationDate() {
return LocalDateTime.now().plusHours(2).toInstant(ZoneOffset.of("-03:00"));
}
public String generateToken(Usuario usuario) {
try {
Algorithm algorithm = Algorithm.HMAC256(tokenKey);
return JWT.create()
.withIssuer("FATEC API")
.withSubject(usuario.getNomeDeUsuario())
.withExpiresAt(this.expirationDate())
.sign(algorithm);
} catch (JWTCreationException exception) {
throw new RuntimeException("Erro ao gerar JWT");
}
}
public String getSuject(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(tokenKey);
return JWT.require(algorithm)
.withIssuer("FATEC API")
.build()
.verify(token)
.getSubject();
} catch (JWTVerificationException exception) {
throw new RuntimeException("Token Inválido");
}
}
}