- Added extractSubject() and getClaimValue() methods

- Updated token generator to use User object instead of username
This commit is contained in:
Max W. 2024-04-24 21:47:03 +02:00
parent c0f0467e4a
commit b51250ffd3

View File

@ -46,19 +46,20 @@ public class AuthenticationService {
} }
Optional<User> user = userRepository.retrieveUserByUsername(username); Optional<User> user = userRepository.retrieveUserByUsername(username);
if (user.isPresent() && passwordEncoder.matches(password, user.get().getPassword())) { if (user.isPresent() && passwordEncoder.matches(password, user.get().getPassword())) {
return generateToken(username); return generateToken(user.get());
} }
return null; return null;
} }
private String generateToken(String username) { private String generateToken(User username) {
long nowMillis = System.currentTimeMillis(); long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis); Date now = new Date(nowMillis);
Date expiryDate = new Date(nowMillis + expirationTime); Date expiryDate = new Date(nowMillis + expirationTime);
return Jwts.builder() return Jwts.builder()
.subject(username) .subject(username.getUsername())
.issuedAt(now) .issuedAt(now)
.claim("role", username.getRole())
.expiration(expiryDate) .expiration(expiryDate)
.signWith(secretKey) .signWith(secretKey)
.compact(); .compact();
@ -73,4 +74,28 @@ public class AuthenticationService {
return false; return false;
} }
} }
public String extractSubject(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getSubject();
}
/**
* Retrieves a typed claim from the JWT.
* @param token the JWT from which to extract the claim
* @param claimName the name of the claim to retrieve
* @param claimType the Class object of the type T of the claim
* @param <T> the expected type of the claim value
* @return the value of the specified claim as type T, or null if not found or in case of an error
* Usage example: getClaimValue(token, "role", String.class)
*/
public <T> T getClaimValue(String token, String claimName, Class<T> claimType) {
try {
Jwt<?, ?> jwt = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token);
Claims claims = (Claims) jwt.getPayload();
return claims.get(claimName, claimType);
} catch (Exception e) {
log.error("Error parsing claims from token: ", e);
return null;
}
}
} }