refactor(api): use refresh token IDs in the database (#2762)
This commit is contained in:
@@ -22,10 +22,13 @@ import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.ParseException;
|
||||
import java.time.Instant;
|
||||
import java.util.Date;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@@ -36,21 +39,21 @@ public class JwtUtils {
|
||||
private static final int MIN_SECRET_BYTES = 32;
|
||||
private static final String JWT_ISSUER = "booklore";
|
||||
|
||||
private static final String CLAIM_USER_ID = "userId";
|
||||
private static final String CLAIM_SCOPE = "scope";
|
||||
|
||||
private DefaultJWTClaimsVerifier<?> claimsVerifier;
|
||||
|
||||
@Getter
|
||||
public static final long accessTokenExpirationMs = 1000L * 60 * 60 * 2; // 2 hours
|
||||
@Getter
|
||||
public static final long refreshTokenExpirationMs = 1000L * 60 * 60 * 24 * 30; // 30 days
|
||||
|
||||
private static final long refreshTokenNotBeforeMs = 1000L * 60 * 2; // 2 minutes
|
||||
private static final Set<String> ACCESS_TOKEN_SCOPES = Set.of("api");
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
validateSecret();
|
||||
this.claimsVerifier = new DefaultJWTClaimsVerifier<>(
|
||||
new JWTClaimsSet.Builder().issuer(JWT_ISSUER).build(),
|
||||
Set.of("exp", "iat", "iss", "sub", "userId")
|
||||
Set.of("exp", "iat", "iss", "sub", CLAIM_USER_ID)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -74,8 +77,7 @@ public class JwtUtils {
|
||||
return key;
|
||||
}
|
||||
|
||||
public String generateToken(BookLoreUserEntity user, boolean isRefreshToken) {
|
||||
long expirationTime = isRefreshToken ? refreshTokenExpirationMs : accessTokenExpirationMs;
|
||||
public String generateToken(BookLoreUserEntity user, long notBeforeMs, long expirationMs, Set<String> scopes) {
|
||||
Instant now = Instant.now();
|
||||
|
||||
try {
|
||||
@@ -85,16 +87,12 @@ public class JwtUtils {
|
||||
.issuer(JWT_ISSUER)
|
||||
.jwtID(UUID.randomUUID().toString())
|
||||
.subject(user.getUsername())
|
||||
.claim("userId", user.getId())
|
||||
.claim(CLAIM_USER_ID, user.getId())
|
||||
.claim(CLAIM_SCOPE, String.join(" ", scopes))
|
||||
.claim("isDefaultPassword", user.isDefaultPassword())
|
||||
.issueTime(Date.from(now))
|
||||
.expirationTime(Date.from(now.plusMillis(expirationTime)));
|
||||
|
||||
if (isRefreshToken) {
|
||||
// Prevent refresh tokens from being used until at least
|
||||
// some `refreshTokenNotBeforeMs` milliseconds from now.
|
||||
builder.notBeforeTime(Date.from(now.plusMillis(refreshTokenNotBeforeMs)));
|
||||
}
|
||||
.notBeforeTime(Date.from(now.plusMillis(notBeforeMs)))
|
||||
.expirationTime(Date.from(now.plusMillis(expirationMs)));
|
||||
|
||||
JWTClaimsSet claimsSet = builder.build();
|
||||
|
||||
@@ -112,11 +110,7 @@ public class JwtUtils {
|
||||
}
|
||||
|
||||
public String generateAccessToken(BookLoreUserEntity user) {
|
||||
return generateToken(user, false);
|
||||
}
|
||||
|
||||
public String generateRefreshToken(BookLoreUserEntity user) {
|
||||
return generateToken(user, true);
|
||||
return generateToken(user, 0, accessTokenExpirationMs, ACCESS_TOKEN_SCOPES);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -128,7 +122,6 @@ public class JwtUtils {
|
||||
try {
|
||||
signedJWT = SignedJWT.parse(token);
|
||||
} catch (Exception e) {
|
||||
log.error("Malformed token", e);
|
||||
throw ApiError.JWT_INVALID.createException("Malformed token");
|
||||
}
|
||||
|
||||
@@ -142,11 +135,19 @@ public class JwtUtils {
|
||||
/**
|
||||
* Validates the token's signature, expiration, and issuer.
|
||||
*/
|
||||
public boolean validateToken(String token) {
|
||||
public boolean validateAccessToken(String token) {
|
||||
return validateToken(token, ACCESS_TOKEN_SCOPES);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the token's signature, expiration, issuer, and scopes.
|
||||
*/
|
||||
public boolean validateToken(String token, Set<String> requiredScopes) {
|
||||
try {
|
||||
SignedJWT signedJWT = parseAndVerify(token);
|
||||
JWTClaimsSet claims = signedJWT.getJWTClaimsSet();
|
||||
validateClaims(claims);
|
||||
validateScopes(claims, requiredScopes);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("Invalid token: {}", e.getMessage());
|
||||
@@ -160,22 +161,41 @@ public class JwtUtils {
|
||||
*/
|
||||
private void validateClaims(JWTClaimsSet claims) throws BadJWTException {
|
||||
claimsVerifier.verify(claims, null);
|
||||
Object userId = claims.getClaim("userId");
|
||||
Object userId = claims.getClaim(CLAIM_USER_ID);
|
||||
if (!(userId instanceof Number)) {
|
||||
throw new BadJWTException("Invalid userId claim type");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateScopes(JWTClaimsSet claims, Set<String> requiredScopes) throws BadJWTException {
|
||||
if (requiredScopes.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
var scopeClaimStr = claims.getClaimAsString(CLAIM_SCOPE);
|
||||
scopeClaimStr = scopeClaimStr == null ? "" : scopeClaimStr;
|
||||
|
||||
var scopeClaim = Set.of(scopeClaimStr.trim().split(" +"));
|
||||
|
||||
if (!scopeClaim.containsAll(requiredScopes)) {
|
||||
throw new BadJWTException("Lacks expected scopes");
|
||||
}
|
||||
} catch (ParseException e) {
|
||||
throw new BadJWTException("Lacks expected scopes");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts claims from a token after verifying signature and validating expiration/issuer.
|
||||
* @throws RuntimeException if token is invalid or expired.
|
||||
* Extracts claims from a token after verifying signature.
|
||||
* Does not validate if the token is expired or otherwise revoked.
|
||||
*
|
||||
* @throws RuntimeException if token is invalid
|
||||
*/
|
||||
public JWTClaimsSet extractClaims(String token) {
|
||||
private JWTClaimsSet unsafeExtractClaims(String token) {
|
||||
try {
|
||||
SignedJWT signedJWT = parseAndVerify(token);
|
||||
JWTClaimsSet claims = signedJWT.getJWTClaimsSet();
|
||||
validateClaims(claims);
|
||||
return claims;
|
||||
return signedJWT.getJWTClaimsSet();
|
||||
} catch (BadJWTException e) {
|
||||
throw ApiError.JWT_INVALID.createException(e.getMessage());
|
||||
} catch (Exception e) {
|
||||
@@ -185,12 +205,22 @@ public class JwtUtils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts username from token.
|
||||
* @throws RuntimeException if token is invalid or expired.
|
||||
* Extracts JWT ID from a token after verifying signature.
|
||||
* Does not validate if the token is expired or otherwise revoked.
|
||||
*
|
||||
* @throws RuntimeException if token is invalid
|
||||
*/
|
||||
public String extractUsername(String token) {
|
||||
public String unsafeExtractJWTID(String token) {
|
||||
return unsafeExtractClaims(token).getJWTID();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts username from token.
|
||||
* @throws RuntimeException if token is invalid
|
||||
*/
|
||||
public String unsafeExtractUsername(String token) {
|
||||
try {
|
||||
return extractClaims(token).getSubject();
|
||||
return unsafeExtractClaims(token).getSubject();
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to extract username from token: {}", e.getMessage());
|
||||
throw e;
|
||||
@@ -199,12 +229,12 @@ public class JwtUtils {
|
||||
|
||||
/**
|
||||
* Extracts user ID from token.
|
||||
* @throws RuntimeException if token is invalid or expired.
|
||||
* @throws RuntimeException if token is invalid
|
||||
*/
|
||||
public Long extractUserId(String token) {
|
||||
Object userIdClaim = extractClaims(token).getClaim("userId");
|
||||
if (userIdClaim instanceof Number) {
|
||||
return ((Number) userIdClaim).longValue();
|
||||
public long unsafeExtractUserId(String token) {
|
||||
Object userIdClaim = unsafeExtractClaims(token).getClaim(CLAIM_USER_ID);
|
||||
if (userIdClaim instanceof Number userIdNumber) {
|
||||
return userIdNumber.longValue();
|
||||
}
|
||||
throw ApiError.JWT_INVALID.createException("Invalid userId claim type");
|
||||
}
|
||||
|
||||
+4
-4
@@ -46,8 +46,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
if (jwtUtils.validateAccessToken(token)) {
|
||||
setUserFromToken(token, request);
|
||||
} else {
|
||||
log.debug("Invalid token. Rejecting request.");
|
||||
}
|
||||
@@ -57,8 +57,8 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private void authenticateUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
private void setUserFromToken(String token, HttpServletRequest request) {
|
||||
long userId = jwtUtils.unsafeExtractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId).orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, null);
|
||||
|
||||
+4
-4
@@ -47,8 +47,8 @@ public class QueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
}
|
||||
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
authenticateUser(token, request);
|
||||
if (jwtUtils.validateAccessToken(token)) {
|
||||
setUserFromToken(token, request);
|
||||
} else {
|
||||
log.debug("Invalid token. Rejecting request.");
|
||||
}
|
||||
@@ -59,8 +59,8 @@ public class QueryParameterJwtFilter extends OncePerRequestFilter {
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
protected void authenticateUser(String token, HttpServletRequest request) {
|
||||
Long userId = jwtUtils.extractUserId(token);
|
||||
protected void setUserFromToken(String token, HttpServletRequest request) {
|
||||
long userId = jwtUtils.unsafeExtractUserId(token);
|
||||
BookLoreUserEntity entity = userRepository.findByIdWithDetails(userId)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found with ID: " + userId));
|
||||
BookLoreUser user = bookLoreUserTransformer.toDTO(entity);
|
||||
|
||||
+2
-2
@@ -99,8 +99,8 @@ public class WebSocketAuthInterceptor implements ChannelInterceptor {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (jwtUtils.validateToken(token)) {
|
||||
String username = jwtUtils.extractUsername(token);
|
||||
if (jwtUtils.validateAccessToken(token)) {
|
||||
String username = jwtUtils.unsafeExtractUsername(token);
|
||||
if (username != null && !username.isBlank()) {
|
||||
return new UsernamePasswordAuthenticationToken(username, null, List.of());
|
||||
}
|
||||
|
||||
+4
-7
@@ -3,13 +3,13 @@ package org.booklore.config.security.oidc;
|
||||
import com.nimbusds.jwt.JWTClaimsSet;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.service.RefreshTokenService;
|
||||
import org.booklore.exception.ApiError;
|
||||
import org.booklore.model.dto.settings.OidcProviderDetails;
|
||||
import org.booklore.model.entity.OidcSessionEntity;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.model.websocket.Topic;
|
||||
import org.booklore.repository.OidcSessionRepository;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.service.NotificationService;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
@@ -37,7 +37,7 @@ public class BackchannelLogoutService {
|
||||
private final AppSettingService appSettingService;
|
||||
private final OidcTokenValidator oidcTokenValidator;
|
||||
private final OidcSessionRepository oidcSessionRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
private final NotificationService notificationService;
|
||||
private final AuditService auditService;
|
||||
|
||||
@@ -89,11 +89,8 @@ public class BackchannelLogoutService {
|
||||
oidcSessionRepository.save(session);
|
||||
|
||||
var user = session.getUser();
|
||||
refreshTokenRepository.findAllByUserAndRevokedFalse(user).forEach(token -> {
|
||||
token.setRevoked(true);
|
||||
token.setRevocationDate(Instant.now());
|
||||
refreshTokenRepository.save(token);
|
||||
});
|
||||
|
||||
refreshTokenService.revokeAllForUser(user);
|
||||
|
||||
notificationService.sendMessageToUser(
|
||||
user.getUsername(),
|
||||
|
||||
+12
-38
@@ -15,7 +15,6 @@ import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.RefreshTokenEntity;
|
||||
import org.booklore.model.enums.ProvisioningMethod;
|
||||
import org.booklore.model.enums.UserPermission;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.user.DefaultSettingInitializer;
|
||||
@@ -42,7 +41,7 @@ public class AuthenticationService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final UserRepository userRepository;
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
private final UserProvisioningService userProvisioningService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final JwtUtils jwtUtils;
|
||||
@@ -54,7 +53,7 @@ public class AuthenticationService {
|
||||
public AuthenticationService(
|
||||
AppProperties appProperties,
|
||||
UserRepository userRepository,
|
||||
RefreshTokenRepository refreshTokenRepository,
|
||||
RefreshTokenService refreshTokenService,
|
||||
UserProvisioningService userProvisioningService,
|
||||
PasswordEncoder passwordEncoder,
|
||||
JwtUtils jwtUtils,
|
||||
@@ -65,7 +64,7 @@ public class AuthenticationService {
|
||||
) {
|
||||
this.appProperties = appProperties;
|
||||
this.userRepository = userRepository;
|
||||
this.refreshTokenRepository = refreshTokenRepository;
|
||||
this.refreshTokenService = refreshTokenService;
|
||||
this.userProvisioningService = userProvisioningService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.jwtUtils = jwtUtils;
|
||||
@@ -191,25 +190,17 @@ public class AuthenticationService {
|
||||
|
||||
public ResponseEntity<AccessTokenDto> loginUser(BookLoreUserEntity user, Long customRefreshTokenExpirationMs) {
|
||||
String accessToken = jwtUtils.generateAccessToken(user);
|
||||
String refreshToken = jwtUtils.generateRefreshToken(user);
|
||||
|
||||
long expirationMs = customRefreshTokenExpirationMs != null ? customRefreshTokenExpirationMs : jwtUtils.getRefreshTokenExpirationMs();
|
||||
var refreshToken = customRefreshTokenExpirationMs == null ?
|
||||
refreshTokenService.createRefreshToken(user)
|
||||
: refreshTokenService.createRefreshToken(user, customRefreshTokenExpirationMs);
|
||||
|
||||
RefreshTokenEntity refreshTokenEntity = RefreshTokenEntity.builder()
|
||||
.user(user)
|
||||
.token(refreshToken)
|
||||
.expiryDate(Instant.now().plusMillis(expirationMs))
|
||||
.revoked(false)
|
||||
.build();
|
||||
|
||||
refreshTokenRepository.save(refreshTokenEntity);
|
||||
auditService.log(AuditAction.LOGIN_SUCCESS, "User", user.getId(), "Login successful for user: " + user.getUsername());
|
||||
|
||||
|
||||
return ResponseEntity.ok(
|
||||
AccessTokenDto.builder()
|
||||
.accessToken(jwtUtils.generateAccessToken(user))
|
||||
.refreshToken(refreshTokenEntity.getToken())
|
||||
.accessToken(accessToken)
|
||||
.refreshToken(refreshToken)
|
||||
.expires(JwtUtils.getAccessTokenExpirationMs() / 1000)
|
||||
.isDefaultPassword(user.isDefaultPassword())
|
||||
.build()
|
||||
@@ -221,31 +212,14 @@ public class AuthenticationService {
|
||||
String ip = RequestUtils.getCurrentRequest().getRemoteAddr();
|
||||
authRateLimitService.checkRefreshRateLimit(ip);
|
||||
|
||||
RefreshTokenEntity storedToken = refreshTokenRepository.findByToken(token).orElseThrow(() -> {
|
||||
authRateLimitService.recordFailedRefreshAttempt(ip);
|
||||
return ApiError.INVALID_CREDENTIALS.createException("Refresh token not found");
|
||||
});
|
||||
|
||||
if (storedToken.isRevoked() || storedToken.getExpiryDate().isBefore(Instant.now()) || !jwtUtils.validateToken(token)) {
|
||||
RefreshTokenEntity storedTokenEntity = refreshTokenService.findByToken(token).orElseThrow(() -> {
|
||||
authRateLimitService.recordFailedRefreshAttempt(ip);
|
||||
throw ApiError.INVALID_CREDENTIALS.createException("Invalid or expired refresh token");
|
||||
}
|
||||
});
|
||||
|
||||
BookLoreUserEntity user = storedToken.getUser();
|
||||
BookLoreUserEntity user = storedTokenEntity.getUser();
|
||||
|
||||
storedToken.setRevoked(true);
|
||||
storedToken.setRevocationDate(Instant.now());
|
||||
refreshTokenRepository.save(storedToken);
|
||||
|
||||
String newRefreshToken = jwtUtils.generateRefreshToken(user);
|
||||
RefreshTokenEntity newRefreshTokenEntity = RefreshTokenEntity.builder()
|
||||
.user(user)
|
||||
.token(newRefreshToken)
|
||||
.expiryDate(Instant.now().plusMillis(jwtUtils.getRefreshTokenExpirationMs()))
|
||||
.revoked(false)
|
||||
.build();
|
||||
|
||||
refreshTokenRepository.save(newRefreshTokenEntity);
|
||||
var newRefreshToken = refreshTokenService.refresh(storedTokenEntity);
|
||||
|
||||
authRateLimitService.resetRefreshAttempts(ip);
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import org.booklore.model.entity.RefreshTokenEntity;
|
||||
import org.booklore.model.enums.AuditAction;
|
||||
import org.booklore.model.enums.ProvisioningMethod;
|
||||
import org.booklore.repository.OidcSessionRepository;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.repository.UserRepository;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import org.booklore.service.audit.AuditService;
|
||||
@@ -28,7 +27,7 @@ import java.util.List;
|
||||
@AllArgsConstructor
|
||||
public class LogoutService {
|
||||
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final RefreshTokenService refreshTokenService;
|
||||
private final OidcSessionRepository oidcSessionRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final AppSettingService appSettingService;
|
||||
@@ -59,7 +58,7 @@ public class LogoutService {
|
||||
}
|
||||
|
||||
if (refreshToken != null && !refreshToken.isBlank()) {
|
||||
RefreshTokenEntity tokenEntity = refreshTokenRepository.findByToken(refreshToken)
|
||||
RefreshTokenEntity tokenEntity = refreshTokenService.findByToken(refreshToken)
|
||||
.orElseThrow(() -> ApiError.GENERIC_UNAUTHORIZED.createException("Invalid refresh token"));
|
||||
return tokenEntity.getUser();
|
||||
}
|
||||
@@ -68,12 +67,7 @@ public class LogoutService {
|
||||
}
|
||||
|
||||
private void revokeRefreshToken(BookLoreUserEntity user) {
|
||||
List<RefreshTokenEntity> tokens = refreshTokenRepository.findAllByUserAndRevokedFalse(user);
|
||||
tokens.forEach(token -> {
|
||||
token.setRevoked(true);
|
||||
token.setRevocationDate(Instant.now());
|
||||
});
|
||||
refreshTokenRepository.saveAll(tokens);
|
||||
refreshTokenService.revokeAllForUser(user);
|
||||
}
|
||||
|
||||
private String buildOidcLogoutUrl(BookLoreUserEntity user, String origin) {
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package org.booklore.config.security.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.RefreshTokenEntity;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class RefreshTokenService {
|
||||
private static final long DEFAULT_EXPIRATION_MS = 1000L * 60 * 60 * 24 * 30; // 30 days
|
||||
private static final long DEFAULT_NOT_BEFORE_MS = 1000L * 60 * 2; // 2 minutes
|
||||
private static final Set<String> REFRESH_TOKEN_CLAIMS = Set.of("offline");
|
||||
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
@Transactional
|
||||
public String createRefreshToken(BookLoreUserEntity user) {
|
||||
return createRefreshToken(user, DEFAULT_EXPIRATION_MS);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public String createRefreshToken(BookLoreUserEntity user, long expirationMs) {
|
||||
String token = jwtUtils.generateToken(user, DEFAULT_NOT_BEFORE_MS, expirationMs, REFRESH_TOKEN_CLAIMS);
|
||||
|
||||
String jwtId = jwtUtils.unsafeExtractJWTID(token);
|
||||
|
||||
if (jwtId == null) {
|
||||
// This should not happen during runtime.
|
||||
throw new RuntimeException("Refresh token lacks an ID");
|
||||
}
|
||||
|
||||
RefreshTokenEntity refreshTokenEntity = RefreshTokenEntity.builder()
|
||||
.user(user)
|
||||
.token(jwtId)
|
||||
.expiryDate(Instant.now().plusMillis(expirationMs))
|
||||
.revoked(false)
|
||||
.build();
|
||||
|
||||
refreshTokenRepository.save(refreshTokenEntity);
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
public Optional<RefreshTokenEntity> findByToken(String token) {
|
||||
String jwtId = null;
|
||||
try {
|
||||
// Eventually we probably want to check for the `REFRESH_TOKEN_CLAIMS`
|
||||
// but for now we can assume that it's a refresh token if it's in the database.
|
||||
if (jwtUtils.validateToken(token, Set.of())) {
|
||||
jwtId = jwtUtils.unsafeExtractJWTID(token);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("Invalid JWT", e);
|
||||
}
|
||||
|
||||
if (jwtId == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
var refreshTokenEntity = refreshTokenRepository.findByToken(jwtId);
|
||||
|
||||
// For some reason we store the expiration in the database, too.
|
||||
boolean isRevoked = refreshTokenEntity.map(RefreshTokenEntity::isRevoked).orElse(false);
|
||||
boolean isExpired = refreshTokenEntity.map(t -> t.getExpiryDate().isBefore(Instant.now())).orElse(false);
|
||||
|
||||
if (refreshTokenEntity.isEmpty() || isRevoked || isExpired) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return refreshTokenEntity;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void revokeAllForUser(BookLoreUserEntity user) {
|
||||
var tokens = refreshTokenRepository.findAllByUserAndRevokedFalse(user);
|
||||
|
||||
for (var token : tokens) {
|
||||
revoke(token);
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void revoke(RefreshTokenEntity refreshTokenEntity) {
|
||||
refreshTokenEntity.setRevoked(true);
|
||||
refreshTokenEntity.setRevocationDate(Instant.now());
|
||||
|
||||
refreshTokenRepository.save(refreshTokenEntity);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public String refresh(RefreshTokenEntity refreshTokenEntity) {
|
||||
revoke(refreshTokenEntity);
|
||||
|
||||
return createRefreshToken(refreshTokenEntity.getUser());
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ public class AppMigrationStartup {
|
||||
private final PopulateAuthorSortNameMigration populateAuthorSortNameMigration;
|
||||
private final RemoveBundledCustomSvgIconsMigration removeBundledCustomSvgIconsMigration;
|
||||
private final OIDCClientSecretSeparateKey oidcClientSecretSeparateKey;
|
||||
private final RefreshTokenSwapTokenToJWTID refreshTokenSwapTokenToJWTID;
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void runMigrationsOnce() {
|
||||
@@ -34,5 +35,6 @@ public class AppMigrationStartup {
|
||||
appMigrationService.executeMigration(populateAuthorSortNameMigration);
|
||||
appMigrationService.executeMigration(removeBundledCustomSvgIconsMigration);
|
||||
appMigrationService.executeMigration(oidcClientSecretSeparateKey);
|
||||
appMigrationService.executeMigration(refreshTokenSwapTokenToJWTID);
|
||||
}
|
||||
}
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package org.booklore.service.migration.migrations;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.booklore.config.security.JwtUtils;
|
||||
import org.booklore.model.dto.settings.AppSettingKey;
|
||||
import org.booklore.model.entity.AppSettingEntity;
|
||||
import org.booklore.model.entity.RefreshTokenEntity;
|
||||
import org.booklore.repository.RefreshTokenRepository;
|
||||
import org.booklore.service.migration.Migration;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import tools.jackson.databind.node.ObjectNode;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Set;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RefreshTokenSwapTokenToJWTID implements Migration {
|
||||
private final RefreshTokenRepository refreshTokenRepository;
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
@Override
|
||||
public String getKey() {
|
||||
return "refreshTokenSwapTokenToJWTID";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDescription() {
|
||||
return "Migrates Refresh Tokens to only storing the JWT ID rather than the full token.";
|
||||
}
|
||||
|
||||
public String getJWTID(String token) {
|
||||
try {
|
||||
return jwtUtils.unsafeExtractJWTID(token);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public void migrate(RefreshTokenEntity refreshTokenEntity) {
|
||||
String jwtID = getJWTID(refreshTokenEntity.getToken());
|
||||
|
||||
if (jwtID == null || jwtID.isBlank()) {
|
||||
// Skip non-token.
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
refreshTokenEntity.setToken(jwtID);
|
||||
refreshTokenRepository.save(refreshTokenEntity);
|
||||
} catch (Exception e) {
|
||||
// If there were any issues revoke this token.
|
||||
log.warn("Error getting JWT ID from token", e);
|
||||
refreshTokenEntity.setRevocationDate(Instant.now());
|
||||
refreshTokenEntity.setRevoked(true);
|
||||
refreshTokenRepository.save(refreshTokenEntity);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute() {
|
||||
log.info("Executing migration: {}", getKey());
|
||||
|
||||
Pageable pageable = PageRequest.of(0, 10, Sort.by("id"));
|
||||
Page<RefreshTokenEntity> refreshTokenEntities;
|
||||
do {
|
||||
refreshTokenEntities = refreshTokenRepository.findAll(pageable);
|
||||
|
||||
for (var refreshTokenEntity : refreshTokenEntities) {
|
||||
migrate(refreshTokenEntity);
|
||||
}
|
||||
|
||||
pageable = refreshTokenEntities.nextPageable();
|
||||
} while (refreshTokenEntities.hasNext());
|
||||
|
||||
log.info("Completed migration: {}", getKey());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user