diff --git a/src/main/java/de/w665/sharepulse/service/AuthenticationService.java b/src/main/java/de/w665/sharepulse/service/AuthenticationService.java index 08a47b6..6df00ce 100644 --- a/src/main/java/de/w665/sharepulse/service/AuthenticationService.java +++ b/src/main/java/de/w665/sharepulse/service/AuthenticationService.java @@ -46,19 +46,20 @@ public class AuthenticationService { } Optional user = userRepository.retrieveUserByUsername(username); if (user.isPresent() && passwordEncoder.matches(password, user.get().getPassword())) { - return generateToken(username); + return generateToken(user.get()); } return null; } - private String generateToken(String username) { + private String generateToken(User username) { long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Date expiryDate = new Date(nowMillis + expirationTime); return Jwts.builder() - .subject(username) + .subject(username.getUsername()) .issuedAt(now) + .claim("role", username.getRole()) .expiration(expiryDate) .signWith(secretKey) .compact(); @@ -73,4 +74,28 @@ public class AuthenticationService { 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 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 getClaimValue(String token, String claimName, Class 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; + } + } }