|
|
@@ -3,7 +3,12 @@ package com.danielbohry.authservice.service.auth;
|
|
|
import io.jsonwebtoken.Claims;
|
|
|
import io.jsonwebtoken.ExpiredJwtException;
|
|
|
import io.jsonwebtoken.Jwts;
|
|
|
-import io.jsonwebtoken.SignatureAlgorithm;
|
|
|
+import io.jsonwebtoken.security.Keys;
|
|
|
+
|
|
|
+import javax.crypto.SecretKey;
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.security.MessageDigest;
|
|
|
+import java.security.NoSuchAlgorithmException;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
import org.springframework.security.core.GrantedAuthority;
|
|
|
@@ -32,6 +37,16 @@ public class JwtService {
|
|
|
|
|
|
private static final List<String> ROLE_PRIORITY = List.of("ADMIN", "SERVICE", "VPN");
|
|
|
|
|
|
+ private SecretKey getSigningKey() {
|
|
|
+ try {
|
|
|
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
|
|
+ byte[] keyBytes = digest.digest(secret.getBytes(StandardCharsets.UTF_8));
|
|
|
+ return Keys.hmacShaKeyFor(keyBytes);
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ throw new RuntimeException("SHA-256 algorithm not available", e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
public String extractUsername(String token) {
|
|
|
return extractClaim(token, Claims::getSubject);
|
|
|
}
|
|
|
@@ -66,11 +81,13 @@ public class JwtService {
|
|
|
|
|
|
private Authentication generateToken(Map<String, Object> claims, UserDetails userDetails) {
|
|
|
Date expirationDate = new Date(currentTimeMillis() + 1000 * 60 * 60 * hoursByRole(claims));
|
|
|
- String token = Jwts.builder().setClaims(claims)
|
|
|
- .setSubject(userDetails.getUsername())
|
|
|
- .setIssuedAt(new Date(currentTimeMillis()))
|
|
|
- .setExpiration(expirationDate)
|
|
|
- .signWith(SignatureAlgorithm.HS256, secret).compact();
|
|
|
+ String token = Jwts.builder()
|
|
|
+ .claims(claims)
|
|
|
+ .subject(userDetails.getUsername())
|
|
|
+ .issuedAt(new Date(currentTimeMillis()))
|
|
|
+ .expiration(expirationDate)
|
|
|
+ .signWith(getSigningKey())
|
|
|
+ .compact();
|
|
|
|
|
|
return new Authentication(token,
|
|
|
expirationDate.toInstant(),
|
|
|
@@ -82,9 +99,10 @@ public class JwtService {
|
|
|
private Claims extractAllClaims(String token) {
|
|
|
try {
|
|
|
return Jwts.parser()
|
|
|
- .setSigningKey(secret)
|
|
|
- .parseClaimsJws(token)
|
|
|
- .getBody();
|
|
|
+ .verifyWith(getSigningKey())
|
|
|
+ .build()
|
|
|
+ .parseSignedClaims(token)
|
|
|
+ .getPayload();
|
|
|
} catch (ExpiredJwtException e) {
|
|
|
log.warn("Expired JWT token [{}]", e.getClaims());
|
|
|
return e.getClaims();
|