fix: avoid parsing access token on frontend during login (#1201)

This commit is contained in:
James Ward
2026-05-09 17:05:39 -04:00
committed by GitHub
parent da0d41bace
commit 60ffb09795
20 changed files with 170 additions and 117 deletions
@@ -5,6 +5,7 @@ import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.AccessTokenDto;
import org.booklore.model.dto.settings.OidcAutoProvisionDetails;
import org.booklore.model.dto.settings.OidcProviderDetails;
import org.booklore.model.entity.BookLoreUserEntity;
@@ -26,7 +27,6 @@ import jakarta.servlet.http.HttpServletRequest;
import java.net.URI;
import java.text.ParseException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantLock;
@@ -55,7 +55,7 @@ public class OidcAuthService {
private static final ConcurrentMap<String, ReentrantLock> userLocks = new ConcurrentHashMap<>();
@Transactional
public ResponseEntity<Map<String, String>> exchangeCodeForTokens(
public ResponseEntity<AccessTokenDto> exchangeCodeForTokens(
String code,
String codeVerifier,
String redirectUri,
@@ -101,7 +101,7 @@ public class OidcAuthService {
persistOidcSession(user, userClaims.subject(), providerDetails.getIssuerUri(), tokenResponse, idToken, claims);
String durationStr = appSettingService.getSettingValue("oidc_session_duration_hours");
ResponseEntity<Map<String, String>> response;
ResponseEntity<AccessTokenDto> response;
if (durationStr != null && !durationStr.isBlank()) {
try {
long durationMs = Long.parseLong(durationStr) * 3_600_000L;
@@ -2,6 +2,7 @@ package org.booklore.config.security.service;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.booklore.model.dto.AccessTokenDto;
import org.springframework.context.annotation.Lazy;
import org.booklore.config.AppProperties;
import org.booklore.config.security.JwtUtils;
@@ -27,7 +28,6 @@ import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.booklore.model.enums.AuditAction;
import org.booklore.service.audit.AuditService;
@@ -126,7 +126,7 @@ public class AuthenticationService {
}
@Transactional
public ResponseEntity<Map<String, String>> loginUser(UserLoginRequest loginRequest) {
public ResponseEntity<AccessTokenDto> loginUser(UserLoginRequest loginRequest) {
if (appSettingService.getAppSettings().isOidcForceOnlyMode()) {
BookLoreUserEntity oidcCheckUser = userRepository.findByUsername(loginRequest.getUsername()).orElse(null);
if (oidcCheckUser == null || !oidcCheckUser.getPermissions().isPermissionAdmin()) {
@@ -164,7 +164,7 @@ public class AuthenticationService {
}
@Transactional
public ResponseEntity<Map<String, String>> loginRemote(String name, String username, String email, String groups) {
public ResponseEntity<AccessTokenDto> loginRemote(String name, String username, String email, String groups) {
if (username == null || username.isEmpty()) {
throw ApiError.GENERIC_BAD_REQUEST.createException("Remote-User header is missing");
}
@@ -181,11 +181,11 @@ public class AuthenticationService {
return loginUser(user.get());
}
public ResponseEntity<Map<String, String>> loginUser(BookLoreUserEntity user) {
public ResponseEntity<AccessTokenDto> loginUser(BookLoreUserEntity user) {
return loginUser(user, null);
}
public ResponseEntity<Map<String, String>> loginUser(BookLoreUserEntity user, Long customRefreshTokenExpirationMs) {
public ResponseEntity<AccessTokenDto> loginUser(BookLoreUserEntity user, Long customRefreshTokenExpirationMs) {
String accessToken = jwtUtils.generateAccessToken(user);
String refreshToken = jwtUtils.generateRefreshToken(user);
@@ -201,15 +201,19 @@ public class AuthenticationService {
refreshTokenRepository.save(refreshTokenEntity);
auditService.log(AuditAction.LOGIN_SUCCESS, "User", user.getId(), "Login successful for user: " + user.getUsername());
return ResponseEntity.ok(Map.of(
"accessToken", accessToken,
"refreshToken", refreshTokenEntity.getToken(),
"isDefaultPassword", String.valueOf(user.isDefaultPassword())
));
return ResponseEntity.ok(
AccessTokenDto.builder()
.accessToken(jwtUtils.generateAccessToken(user))
.refreshToken(refreshTokenEntity.getToken())
.expires(JwtUtils.getAccessTokenExpirationMs() / 1000)
.isDefaultPassword(user.isDefaultPassword())
.build()
);
}
@Transactional
public ResponseEntity<Map<String, String>> refreshToken(String token) {
public ResponseEntity<AccessTokenDto> refreshToken(String token) {
String ip = RequestUtils.getCurrentRequest().getRemoteAddr();
authRateLimitService.checkRefreshRateLimit(ip);
@@ -241,9 +245,12 @@ public class AuthenticationService {
authRateLimitService.resetRefreshAttempts(ip);
return ResponseEntity.ok(Map.of(
"accessToken", jwtUtils.generateAccessToken(user),
"refreshToken", newRefreshToken
));
return ResponseEntity.ok(
AccessTokenDto.builder()
.accessToken(jwtUtils.generateAccessToken(user))
.refreshToken(newRefreshToken)
.expires(JwtUtils.getAccessTokenExpirationMs() / 1000)
.build()
);
}
}
@@ -3,6 +3,7 @@ package org.booklore.controller;
import org.booklore.config.AppProperties;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.AccessTokenDto;
import org.booklore.model.dto.UserCreateRequest;
import org.booklore.model.dto.request.RefreshTokenRequest;
import org.booklore.model.dto.request.UserLoginRequest;
@@ -22,7 +23,6 @@ import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.Optional;
@Tag(name = "Authentication", description = "Endpoints for user authentication, registration, and token management")
@@ -53,7 +53,7 @@ public class AuthenticationController {
@Operation(summary = "Login user", description = "Authenticate a user and return JWT tokens.")
@ApiResponse(responseCode = "200", description = "User authenticated successfully")
@PostMapping("/login")
public ResponseEntity<Map<String, String>> loginUser(
public ResponseEntity<AccessTokenDto> loginUser(
@Parameter(description = "User login request") @RequestBody @Valid UserLoginRequest loginRequest) {
return authenticationService.loginUser(loginRequest);
}
@@ -61,7 +61,7 @@ public class AuthenticationController {
@Operation(summary = "Refresh JWT token", description = "Refresh the JWT token using a valid refresh token.")
@ApiResponse(responseCode = "200", description = "Token refreshed successfully")
@PostMapping("/refresh")
public ResponseEntity<Map<String, String>> refreshToken(
public ResponseEntity<AccessTokenDto> refreshToken(
@Parameter(description = "Refresh token request") @Valid @RequestBody RefreshTokenRequest request) {
return authenticationService.refreshToken(request.getRefreshToken());
}
@@ -72,7 +72,7 @@ public class AuthenticationController {
@ApiResponse(responseCode = "403", description = "Remote authentication is disabled")
})
@GetMapping("/remote")
public ResponseEntity<Map<String, String>> loginRemote(
public ResponseEntity<AccessTokenDto> loginRemote(
@Parameter(description = "Authentication headers") @RequestHeader HttpHeaders headers) {
if (!appProperties.getRemoteAuth().isEnabled()) {
throw ApiError.REMOTE_AUTH_DISABLED.createException();
@@ -11,6 +11,7 @@ import org.booklore.config.security.oidc.OidcAuthService;
import org.booklore.config.security.oidc.OidcCallbackRequest;
import org.booklore.config.security.oidc.OidcStateService;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.AccessTokenDto;
import org.booklore.model.enums.AuditAction;
import org.booklore.service.audit.AuditService;
import org.springframework.http.HttpHeaders;
@@ -52,7 +53,7 @@ public class OidcAuthController {
operationId = "oidcHandleCallback"
)
@PostMapping("/callback")
public ResponseEntity<Map<String, String>> handleCallback(
public ResponseEntity<AccessTokenDto> handleCallback(
@RequestBody @Valid OidcCallbackRequest request,
HttpServletRequest httpRequest) {
log.info("OIDC callback received");
@@ -90,20 +91,24 @@ public class OidcAuthController {
oidcAuthService.validateAppRedirectUri(appRedirectUri);
try {
ResponseEntity<Map<String, String>> tokenResponse = oidcAuthService.exchangeCodeForTokens(
ResponseEntity<AccessTokenDto> tokenResponse = oidcAuthService.exchangeCodeForTokens(
code, codeVerifier, redirectUri, nonce, httpRequest);
Map<String, String> tokens = tokenResponse.getBody();
AccessTokenDto tokens = tokenResponse.getBody();
if (tokens == null) {
throw ApiError.GENERIC_UNAUTHORIZED.createException("Failed to obtain tokens");
}
StringBuilder fragment = new StringBuilder();
fragment.append("access_token=").append(URLEncoder.encode(tokens.get("accessToken"), StandardCharsets.UTF_8));
fragment.append("&refresh_token=").append(URLEncoder.encode(tokens.get("refreshToken"), StandardCharsets.UTF_8));
fragment.append("access_token=").append(URLEncoder.encode(tokens.getAccessToken(), StandardCharsets.UTF_8));
fragment.append("&refresh_token=").append(URLEncoder.encode(tokens.getRefreshToken(), StandardCharsets.UTF_8));
if (tokens.containsKey("isDefaultPassword")) {
fragment.append("&is_default_password=").append(URLEncoder.encode(tokens.get("isDefaultPassword"), StandardCharsets.UTF_8));
if (tokens.getIsDefaultPassword() != null) {
fragment.append("&is_default_password=").append(URLEncoder.encode(tokens.getIsDefaultPassword().toString(), StandardCharsets.UTF_8));
}
if (tokens.getExpires() != null) {
fragment.append("&expires_in=").append(URLEncoder.encode(tokens.getExpires().toString(), StandardCharsets.UTF_8));
}
String redirectUrl = appRedirectUri + "#" + fragment;
@@ -128,7 +133,7 @@ public class OidcAuthController {
operationId = "oidcHandleMobileCallback"
)
@PostMapping("/mobile/callback")
public ResponseEntity<Map<String, String>> handleMobileCallback(
public ResponseEntity<AccessTokenDto> handleMobileCallback(
@RequestParam("code") String code,
@RequestParam("code_verifier") String codeVerifier,
@RequestParam("redirect_uri") String redirectUri,
@@ -0,0 +1,19 @@
package org.booklore.model.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AccessTokenDto {
private String accessToken;
private String refreshToken;
private Long expires;
@Builder.Default
private Boolean isDefaultPassword = null;
}
@@ -3,6 +3,7 @@ package org.booklore.config.security.oidc;
import com.nimbusds.jwt.JWTClaimsSet;
import org.booklore.config.security.service.AuthenticationService;
import org.booklore.exception.APIException;
import org.booklore.model.dto.AccessTokenDto;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.dto.settings.OidcAutoProvisionDetails;
import org.booklore.model.dto.settings.OidcProviderDetails;
@@ -74,7 +75,7 @@ class OidcAuthServiceTest {
var claims = new JWTClaimsSet.Builder().subject("sub-123").build();
var userClaims = userClaims("jdoe", "sub-123");
var user = existingOidcUser("jdoe", "sub-123");
var expectedResponse = ResponseEntity.ok(Map.of("token", "jwt"));
var expectedResponse = ResponseEntity.ok(AccessTokenDto.builder().accessToken("jwt").build());
when(appSettingService.getAppSettings()).thenReturn(settings);
when(oidcTokenClient.exchangeAuthorizationCode(CODE, CODE_VERIFIER, REDIRECT_URI, settings.getOidcProviderDetails()))
@@ -161,7 +162,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -185,7 +186,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn("8");
when(authenticationService.loginUser(user, 8 * 3_600_000L)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user, 8 * 3_600_000L)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -210,7 +211,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn("not-a-number");
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -234,7 +235,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -280,7 +281,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -310,7 +311,7 @@ class OidcAuthServiceTest {
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.empty());
when(userRepository.findByUsername("jdoe")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -366,7 +367,7 @@ class OidcAuthServiceTest {
when(userProvisioningService.provisionOidcUser("newuser", "newuser@example.com", "New User", "sub-new", ISSUER_URI, null, provisionDetails))
.thenReturn(newUser);
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(newUser)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(newUser)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -421,7 +422,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -451,7 +452,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -481,7 +482,7 @@ class OidcAuthServiceTest {
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.empty());
when(userRepository.findByUsername("jdoe")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, REDIRECT_URI, NONCE, mockRequest());
@@ -508,7 +509,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
var result = oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, "https://example.com/oauth2-callback", NONCE, mockRequest());
@@ -531,7 +532,7 @@ class OidcAuthServiceTest {
when(oidcClaimExtractor.extractClaims(eq(claims), any(), eq(Map.of()))).thenReturn(userClaims);
when(userRepository.findByOidcIssuerAndOidcSubject(ISSUER_URI, "sub-123")).thenReturn(Optional.of(user));
when(appSettingService.getSettingValue("oidc_session_duration_hours")).thenReturn(null);
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(Map.of()));
when(authenticationService.loginUser(user)).thenReturn(ResponseEntity.ok(AccessTokenDto.builder().build()));
var result = oidcAuthService.exchangeCodeForTokens(CODE, CODE_VERIFIER, "booklore://oauth2-callback", NONCE, mockRequest());
@@ -3,6 +3,7 @@ package org.booklore.config.security.service;
import org.booklore.config.AppProperties;
import org.booklore.config.security.JwtUtils;
import org.booklore.exception.APIException;
import org.booklore.model.dto.AccessTokenDto;
import org.booklore.model.dto.request.UserLoginRequest;
import org.booklore.model.dto.settings.AppSettings;
import org.booklore.model.entity.BookLoreUserEntity;
@@ -29,9 +30,7 @@ import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
@@ -139,11 +138,12 @@ class AuthenticationServiceTest {
request.setUsername("admin");
request.setPassword("password");
ResponseEntity<Map<String, String>> response = authenticationService.loginUser(request);
ResponseEntity<AccessTokenDto> response = authenticationService.loginUser(request);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getBody()).containsEntry("accessToken", "access-token");
assertThat(response.getBody()).containsEntry("refreshToken", "refresh-token");
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getAccessToken()).isEqualTo("access-token");
assertThat(response.getBody().getRefreshToken()).isEqualTo("refresh-token");
}
@Test
@@ -170,10 +170,11 @@ class AuthenticationServiceTest {
request.setUsername("normaluser");
request.setPassword("password");
ResponseEntity<Map<String, String>> response = authenticationService.loginUser(request);
ResponseEntity<AccessTokenDto> response = authenticationService.loginUser(request);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getBody()).containsEntry("accessToken", "access-token");
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getAccessToken()).isEqualTo("access-token");
}
@Test
@@ -229,12 +230,14 @@ class AuthenticationServiceTest {
when(jwtUtils.generateRefreshToken(user)).thenReturn("my-refresh-token");
when(refreshTokenRepository.save(any(RefreshTokenEntity.class))).thenAnswer(inv -> inv.getArgument(0));
ResponseEntity<Map<String, String>> response = authenticationService.loginUser(user, 7200000L);
ResponseEntity<AccessTokenDto> response = authenticationService.loginUser(user, 7200000L);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThat(response.getBody())
.containsEntry("accessToken", "my-access-token")
.containsEntry("refreshToken", "my-refresh-token")
.containsEntry("isDefaultPassword", "false");
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getAccessToken()).isEqualTo("my-access-token");
assertThat(response.getBody().getRefreshToken()).isEqualTo("my-refresh-token");
assertThat(response.getBody().getExpires()).isEqualTo(7200);
assertThat(response.getBody().getIsDefaultPassword()).isFalse();
}
}
@@ -5,6 +5,7 @@ import org.booklore.config.security.oidc.OidcAuthService;
import org.booklore.config.security.oidc.OidcCallbackRequest;
import org.booklore.config.security.oidc.OidcStateService;
import org.booklore.exception.APIException;
import org.booklore.model.dto.AccessTokenDto;
import org.booklore.service.audit.AuditService;
import org.booklore.model.enums.AuditAction;
import org.junit.jupiter.api.Test;
@@ -59,15 +60,16 @@ class OidcAuthControllerTest {
@Test
void handleCallback_validatesStateAndReturnsTokens() {
var request = new OidcCallbackRequest("code1", "verifier1", "https://redirect", "nonce1", "state1");
var tokenResponse = ResponseEntity.ok(Map.of("accessToken", "at", "refreshToken", "rt"));
var tokenResponse = ResponseEntity.ok(AccessTokenDto.builder().accessToken("at").refreshToken("rt").build());
when(oidcAuthService.exchangeCodeForTokens("code1", "verifier1", "https://redirect", "nonce1", httpRequest))
.thenReturn(tokenResponse);
ResponseEntity<Map<String, String>> response = controller.handleCallback(request, httpRequest);
ResponseEntity<AccessTokenDto> response = controller.handleCallback(request, httpRequest);
verify(oidcStateService).validateAndConsume("state1");
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).containsEntry("accessToken", "at");
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getAccessToken()).isEqualTo("at");
}
@Test
@@ -85,7 +87,7 @@ class OidcAuthControllerTest {
@Test
void handleRedirect_returns302WithFragmentContainingTokens() {
var tokens = Map.of("accessToken", "at123", "refreshToken", "rt456");
var tokens = AccessTokenDto.builder().accessToken("at123").refreshToken("rt456").build();
var tokenResponse = ResponseEntity.ok(tokens);
when(oidcAuthService.exchangeCodeForTokens("code", "verifier", "https://redir", "nonce", httpRequest))
.thenReturn(tokenResponse);
@@ -105,7 +107,7 @@ class OidcAuthControllerTest {
@Test
void handleRedirect_includesIsDefaultPasswordInFragmentWhenPresent() {
var tokens = Map.of("accessToken", "at", "refreshToken", "rt", "isDefaultPassword", "true");
var tokens = AccessTokenDto.builder().accessToken("at").refreshToken("rt").isDefaultPassword(true).build();
var tokenResponse = ResponseEntity.ok(tokens);
when(oidcAuthService.exchangeCodeForTokens("code", "verifier", "https://redir", "nonce", httpRequest))
.thenReturn(tokenResponse);
@@ -114,7 +116,7 @@ class OidcAuthControllerTest {
"code", "verifier", "https://redir", "nonce", "state", "https://app.example.com", httpRequest);
String location = response.getHeaders().getLocation().toString();
assertThat(location).contains("is_default_password=" + URLEncoder.encode("true", StandardCharsets.UTF_8));
assertThat(location).contains("is_default_password=true");
}
@Test
@@ -134,7 +136,7 @@ class OidcAuthControllerTest {
@Test
void handleRedirect_throwsWhenTokenResponseBodyIsNull() {
ResponseEntity<Map<String, String>> tokenResponse = ResponseEntity.ok(null);
ResponseEntity<AccessTokenDto> tokenResponse = ResponseEntity.ok(null);
when(oidcAuthService.exchangeCodeForTokens("code", "verifier", "https://redir", "nonce", httpRequest))
.thenReturn(tokenResponse);
@@ -149,16 +151,17 @@ class OidcAuthControllerTest {
@Test
void handleMobileCallback_validatesStateAndReturnsTokens() {
var tokenResponse = ResponseEntity.ok(Map.of("accessToken", "at", "refreshToken", "rt"));
var tokenResponse = ResponseEntity.ok(AccessTokenDto.builder().accessToken("at").refreshToken("rt").build());
when(oidcAuthService.exchangeCodeForTokens("code", "verifier", "https://redir", "nonce", httpRequest))
.thenReturn(tokenResponse);
ResponseEntity<Map<String, String>> response = controller.handleMobileCallback(
ResponseEntity<AccessTokenDto> response = controller.handleMobileCallback(
"code", "verifier", "https://redir", "nonce", "state", httpRequest);
verify(oidcStateService).validateAndConsume("state");
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody()).containsEntry("accessToken", "at");
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getAccessToken()).isEqualTo("at");
}
@Test
@@ -193,7 +193,7 @@ export async function installLoginAndBooksRoutes(
await asJson(route, {
accessToken: createJwt(),
refreshToken: 'refresh-token',
isDefaultPassword: 'false',
isDefaultPassword: false,
});
return;
}
@@ -107,7 +107,7 @@ describe('initializeAuthFactory', () => {
authService.remoteLogin.mockReturnValue(of({
accessToken: 'access',
refreshToken: 'refresh',
isDefaultPassword: 'false',
isDefaultPassword: false,
}));
const injector = Injector.create({
@@ -5,10 +5,6 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {AuthService} from '../../shared/service/auth.service';
import {AuthGuard} from './auth.guard';
function buildToken(payload: Record<string, unknown>): string {
return `header.${btoa(JSON.stringify(payload))}.signature`;
}
describe('AuthGuard', () => {
const route = {} as ActivatedRouteSnapshot;
const state = {} as RouterStateSnapshot;
@@ -19,6 +15,8 @@ describe('AuthGuard', () => {
const authService = {
getInternalAccessToken: vi.fn<() => string | null>(),
getInternalAccessTokenExpiry: vi.fn<() => number | null>(),
getIsDefaultPassword: vi.fn<() => boolean>(),
};
beforeEach(() => {
@@ -27,6 +25,8 @@ describe('AuthGuard', () => {
router.createUrlTree.mockClear();
router.navigate.mockClear();
authService.getInternalAccessToken.mockReset();
authService.getInternalAccessTokenExpiry.mockReset();
authService.getIsDefaultPassword.mockReset();
TestBed.configureTestingModule({
providers: [
@@ -41,9 +41,8 @@ describe('AuthGuard', () => {
});
it('allows navigation for a valid non-default-password token', () => {
authService.getInternalAccessToken.mockReturnValue(
buildToken({exp: Math.floor(Date.now() / 1000) + 3600})
);
authService.getInternalAccessToken.mockReturnValue('bearer token');
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() + 3600000);
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
@@ -62,9 +61,8 @@ describe('AuthGuard', () => {
it('returns a login UrlTree for expired tokens', () => {
localStorage.setItem('accessToken_Internal', 'stale-token');
authService.getInternalAccessToken.mockReturnValue(
buildToken({exp: Math.floor(Date.now() / 1000) - 10})
);
authService.getInternalAccessToken.mockReturnValue('stale-token');
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() - 10000);
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
@@ -74,24 +72,13 @@ describe('AuthGuard', () => {
});
it('redirects to the change-password flow for default-password tokens', () => {
authService.getInternalAccessToken.mockReturnValue(
buildToken({exp: Math.floor(Date.now() / 1000) + 3600, isDefaultPassword: true})
);
authService.getInternalAccessToken.mockReturnValue('bearer token');
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() + 3600000);
authService.getIsDefaultPassword.mockReturnValue(true);
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
expect(result).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
});
it('clears the token and redirects to login for malformed tokens', () => {
localStorage.setItem('accessToken_Internal', 'bad-token');
authService.getInternalAccessToken.mockReturnValue('bad-token');
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
expect(result).toBe(false);
expect(router.navigate).toHaveBeenCalledWith(['/login']);
expect(localStorage.getItem('accessToken_Internal')).toBeNull();
});
});
+7 -3
View File
@@ -12,15 +12,19 @@ export const AuthGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: R
if (internalAccessToken) {
try {
const payload = JSON.parse(atob(internalAccessToken.split('.')[1]));
if (payload.exp && payload.exp * 1000 < Date.now()) {
const isDefaultPassword = authService.getIsDefaultPassword();
const internalAccessTokenExpiry = authService.getInternalAccessTokenExpiry();
if (internalAccessTokenExpiry != null && internalAccessTokenExpiry < Date.now()) {
localStorage.removeItem('accessToken_Internal');
return router.createUrlTree(['/login']);
}
if (payload.isDefaultPassword) {
if (isDefaultPassword) {
router.navigate(['/change-password']);
return false;
}
return true;
} catch {
localStorage.removeItem('accessToken_Internal');
@@ -110,12 +110,12 @@ describe('OidcCallbackComponent', () => {
oidcService.exchangeCode.mockReturnValue(of({
accessToken: 'access',
refreshToken: 'refresh',
isDefaultPassword: 'true',
isDefaultPassword: true,
}));
configureComponent('?code=code-123&state=state-123');
expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh');
expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh', undefined, true);
expect(authService.initializeWebSocketConnection).toHaveBeenCalledOnce();
expect(sessionStorage.getItem('oidc_redirect_count')).toBeNull();
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
@@ -130,12 +130,12 @@ describe('OidcCallbackComponent', () => {
oidcService.exchangeCode.mockReturnValue(of({
accessToken: 'access',
refreshToken: 'refresh',
isDefaultPassword: 'false',
isDefaultPassword: false,
}));
configureComponent('?code=code-123&state=state-123');
expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh');
expect(authService.saveInternalTokens).toHaveBeenCalledWith('access', 'refresh', undefined, false);
expect(router.navigate).toHaveBeenCalledWith(['/dashboard']);
});
@@ -51,9 +51,9 @@ export class OidcCallbackComponent implements OnInit {
this.oidcService.exchangeCode(code, pkceState.codeVerifier, pkceState.nonce, pkceState.state).subscribe({
next: (response) => {
sessionStorage.removeItem('oidc_redirect_count');
this.authService.saveInternalTokens(response.accessToken, response.refreshToken);
this.authService.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
this.authService.initializeWebSocketConnection();
if (response.isDefaultPassword === 'true') {
if (response.isDefaultPassword) {
this.router.navigate(['/change-password']);
} else {
this.router.navigate(['/dashboard']);
@@ -132,7 +132,7 @@ describe('OidcService', () => {
it('posts the callback payload to exchange an OIDC code for tokens', () => {
const {service, http} = createService();
http.post.mockReturnValue(of({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false'}));
http.post.mockReturnValue(of({accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: false}));
service.exchangeCode('code-123', 'verifier', 'nonce', 'state').subscribe();
@@ -13,7 +13,8 @@ interface OidcPkceState {
interface OidcTokenResponse {
accessToken: string;
refreshToken: string;
isDefaultPassword: string;
isDefaultPassword?: boolean;
expires?: number
}
@Injectable({providedIn: 'root'})
@@ -164,7 +164,7 @@ describe('LoginComponent', () => {
it('navigates to change-password when the server marks the password as default', () => {
configureComponent();
authService.internalLogin.mockReturnValue(of({isDefaultPassword: 'true'}));
authService.internalLogin.mockReturnValue(of({isDefaultPassword: true}));
component.username = 'admin';
component.password = 'password';
@@ -175,7 +175,7 @@ describe('LoginComponent', () => {
it('navigates to the dashboard after a successful non-default-password login', () => {
configureComponent();
authService.internalLogin.mockReturnValue(of({isDefaultPassword: 'false'}));
authService.internalLogin.mockReturnValue(of({isDefaultPassword: false}));
component.username = 'admin';
component.password = 'password';
@@ -126,7 +126,7 @@ export class LoginComponent implements OnInit {
login(): void {
this.authService.internalLogin({username: this.username, password: this.password}).subscribe({
next: (response) => {
if (response.isDefaultPassword === 'true') {
if (response.isDefaultPassword) {
this.router.navigate(['/change-password']);
} else {
this.router.navigate(['/dashboard']);
@@ -67,7 +67,7 @@ describe('AuthService', () => {
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/login`);
expect(request.request.method).toBe('POST');
expect(request.request.body).toEqual({ username: 'admin', password: 'secret' });
request.flush({ accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: 'false' });
request.flush({ accessToken: 'access', refreshToken: 'refresh', isDefaultPassword: false });
expect(service.getInternalAccessToken()).toBe('access');
expect(service.getInternalRefreshToken()).toBe('refresh');
@@ -95,7 +95,7 @@ describe('AuthService', () => {
const request = httpTestingController.expectOne(`${API_CONFIG.BASE_URL}/api/v1/auth/remote`);
expect(request.request.method).toBe('GET');
request.flush({ accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: 'false' });
request.flush({ accessToken: 'remote-access', refreshToken: 'remote-refresh', isDefaultPassword: false });
expect(service.getInternalAccessToken()).toBe('remote-access');
expect(rxStompService.activate).toHaveBeenCalledOnce();
+33 -10
View File
@@ -7,6 +7,13 @@ import { createRxStompConfig } from '../websocket/rx-stomp.config';
import { Router } from '@angular/router';
import { PostLoginInitializerService } from '../../core/services/post-login-initializer.service';
interface AccessTokenResponse {
accessToken: string;
refreshToken: string;
isDefaultPassword?: boolean;
expires?: number;
}
@Injectable({
providedIn: 'root',
})
@@ -27,11 +34,11 @@ export class AuthService {
readonly token = signal<string | null>(this.getInternalAccessToken());
readonly isAuthenticated = computed(() => !!this.token());
internalLogin(credentials: { username: string; password: string }): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.post<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/login`, credentials).pipe(
internalLogin(credentials: { username: string; password: string }): Observable<AccessTokenResponse> {
return this.http.post<AccessTokenResponse>(`${this.apiUrl}/login`, credentials).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
}
@@ -39,22 +46,22 @@ export class AuthService {
);
}
internalRefreshToken(): Observable<{ accessToken: string; refreshToken: string }> {
internalRefreshToken(): Observable<AccessTokenResponse> {
const refreshToken = this.getInternalRefreshToken();
return this.http.post<{ accessToken: string; refreshToken: string }>(`${this.apiUrl}/refresh`, { refreshToken }).pipe(
return this.http.post<AccessTokenResponse>(`${this.apiUrl}/refresh`, { refreshToken }).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
}
})
);
}
remoteLogin(): Observable<{ accessToken: string; refreshToken: string, isDefaultPassword: string }> {
return this.http.get<{ accessToken: string; refreshToken: string, isDefaultPassword: string }>(`${this.apiUrl}/remote`).pipe(
remoteLogin(): Observable<AccessTokenResponse> {
return this.http.get<AccessTokenResponse>(`${this.apiUrl}/remote`).pipe(
tap((response) => {
if (response.accessToken && response.refreshToken) {
this.saveInternalTokens(response.accessToken, response.refreshToken);
this.saveInternalTokens(response.accessToken, response.refreshToken, response.expires, response.isDefaultPassword);
this.initializeWebSocketConnection();
this.handleSuccessfulAuth();
}
@@ -62,12 +69,25 @@ export class AuthService {
);
}
saveInternalTokens(accessToken: string, refreshToken: string): void {
saveInternalTokens(accessToken: string, refreshToken: string, accessTokenExpiry: number = 3600, isDefaultPassword: boolean = false): void {
localStorage.setItem('accessToken_Internal', accessToken);
localStorage.setItem('accessToken_Internal_Expiry', (Date.now() + (accessTokenExpiry * 1000)).toString());
localStorage.setItem('refreshToken_Internal', refreshToken);
localStorage.setItem('authenticationIsDefaultPassword_Internal', isDefaultPassword ? 'true' : 'false')
this.token.set(accessToken);
}
getIsDefaultPassword(): boolean {
const isDefaultPassword = localStorage.getItem('authenticationIsDefaultPassword_Internal') ?? 'false';
return isDefaultPassword === 'true';
}
getInternalAccessTokenExpiry(): number | null {
const expiry = Number.parseInt(localStorage.getItem('accessToken_Internal_Expiry') ?? '');
return Number.isNaN(expiry) ? null : expiry;
}
getInternalAccessToken(): string | null {
return localStorage.getItem('accessToken_Internal');
}
@@ -121,7 +141,10 @@ export class AuthService {
private clearSession(): void {
localStorage.removeItem('accessToken_Internal');
localStorage.removeItem('accessToken_Internal_Expiry');
localStorage.removeItem('refreshToken_Internal');
localStorage.removeItem('authenticationIsDefaultPassword_Internal');
this.token.set(null);
this._postLoginInitialized.set(false);
this.getRxStompService().deactivate();