41 lines
1.2 KiB
Java
41 lines
1.2 KiB
Java
package fr.eni.demo.bll;
|
|
|
|
import io.jsonwebtoken.JwtException;
|
|
import io.jsonwebtoken.Jwts;
|
|
import io.jsonwebtoken.SignatureAlgorithm;
|
|
import io.jsonwebtoken.security.Keys;
|
|
import org.springframework.stereotype.Service;
|
|
|
|
import java.security.Key;
|
|
import java.util.Date;
|
|
|
|
@Service
|
|
public class JwtService {
|
|
|
|
private static final long EXPIRATION_TIME = 86400000; // 1j
|
|
private final Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
|
|
|
|
public String generateToken(String username) {
|
|
return Jwts.builder()
|
|
.setSubject(username)
|
|
.setIssuedAt(new Date())
|
|
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
|
|
.signWith(key)
|
|
.compact();
|
|
}
|
|
|
|
public String extractUsername(String token) {
|
|
return Jwts.parserBuilder().setSigningKey(key).build()
|
|
.parseClaimsJws(token).getBody().getSubject();
|
|
}
|
|
|
|
public boolean isTokenValid(String token) {
|
|
try {
|
|
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
|
|
return true;
|
|
} catch (JwtException e) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|