fix: avoid parsing access token on frontend during login (#1201)
This commit is contained in:
@@ -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;
|
||||
|
||||
+22
-15
@@ -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());
|
||||
|
||||
|
||||
+15
-12
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user