-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenService.java
More file actions
65 lines (57 loc) · 2.12 KB
/
Copy pathTokenService.java
File metadata and controls
65 lines (57 loc) · 2.12 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
package com.exemple.forohub.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.exemple.forohub.model.Usuario;
import com.auth0.jwt.JWTVerifier;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class TokenService {
@Value("${api.security.secret}")
private String apiSecret;
public String generarToken(Usuario usuario) {
try {
Algorithm algorithm = Algorithm.HMAC512(apiSecret);
return JWT.create()
.withIssuer("API ForoHub")
.withSubject(usuario.getCorreoElectronico())
.withExpiresAt(fechaExpiracion())
.sign(algorithm);
} catch (JWTCreationException exception) {
throw new RuntimeException("Error al generar token JWT", exception);
}
}
public boolean isValidToken(String tokenJWT) {
try {
Algorithm algorithm = Algorithm.HMAC512(apiSecret);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("API ForoHub")
.build();
verifier.verify(tokenJWT);
return true;
} catch (JWTVerificationException | IllegalArgumentException exception) {
return false;
}
}
public String getSubject(String tokenJWT) {
try {
Algorithm algorithm = Algorithm.HMAC512(apiSecret);
return JWT.require(algorithm)
.withIssuer("API ForoHub")
.build()
.verify(tokenJWT)
.getSubject();
} catch (JWTVerificationException exception) {
throw new RuntimeException("Token JWT inválido");
}
}
private Instant fechaExpiracion() {
return LocalDateTime.now().plusMinutes(30).toInstant(ZoneOffset.UTC);
}
}