V2: Login Feature (#4701)

This PR migrates the login features from V1 into V2.

  ---
- Login via username/password
- SSO login (Google & GitHub)
-- Fixed issue where users authenticating via SSO (OAuth2/SAML2) were
identified by configurable username attributes (email,
preferred_username, etc.), causing:
  - Duplicate accounts when username attributes changed
  - Authentication failures when claim/NameID configuration changed
  - Data redundancy from same user having multiple accounts
- Added `sso_provider_id` column to store provider's unique identifier
(OIDC sub claim / SAML2 NameID)
- Added `sso_provider` column to store provider name (e.g., "google",
"github", "saml2")
  - User.java:65-69

  Backend Changes:
- Updated UserRepository with findBySsoProviderAndSsoProviderId() method
(UserRepository.java:25)
- Modified UserService.processSSOPostLogin() to implement lookup
priority:
    a. Find by (`ssoProvider`, `ssoProviderId`) first
    b. Fallback to username for backward compatibility
c. Automatically migrate existing users by adding provider IDs
(UserService.java:64-107)
- Updated saveUserCore() to accept and store SSO provider details
(UserService.java:506-566)

  OAuth2 Integration:
- CustomOAuth2UserService: Extracts OIDC sub claim and registration ID
(CustomOAuth2UserService.java:49-59)
- CustomOAuth2AuthenticationSuccessHandler: Passes provider info to
processSSOPostLogin()
(CustomOAuth2AuthenticationSuccessHandler.java:95-108)

  SAML2 Integration:
- CustomSaml2AuthenticationSuccessHandler: Extracts NameID from SAML2
assertion (CustomSaml2AuthenticationSuccessHandler.java:120-133)

  ---
- Configurable Rate Limiting

  Changes:
- Added RateLimit configuration class to ApplicationProperties.Security
(ApplicationProperties.java:314-317)
- Made reset schedule configurable: security.rate-limit.reset-schedule
(default: "0 0 0 * * MON")
- Made max requests configurable: security.rate-limit.max-requests
(default: 1000)
- Updated RateLimitResetScheduler to use @Scheduled(cron =
"${security.rate-limit.reset-schedule:0 0 0 * * MON}")
(RateLimitResetScheduler.java:16)
- Updated SecurityConfiguration.rateLimitingFilter() to use configured
value (SecurityConfiguration.java:377)

  ---
- Enable access without security features

  Backend:
- Added /api/v1/config to permitAll endpoints
(SecurityConfiguration.java:261)
- Config endpoint already returns enableLogin status
(ConfigController.java:60)

  Frontend:
- AuthProvider now checks enableLogin before attempting JWT validation
(UseSession.tsx:98-112)
- If enableLogin=false, skips authentication entirely and sets
session=null
- Landing component bypasses auth check when enableLogin=false
(Landing.tsx:42-46)
- Added createAnonymousUser() and createAnonymousSession() utilities
(springAuthClient.ts:440-464)

Closes #3046
---

## Checklist

### General

- [x] I have read the [Contribution
Guidelines](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/CONTRIBUTING.md)
- [x] I have read the [Stirling-PDF Developer
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md)
(if applicable)
- [x] I have read the [How to add new languages to
Stirling-PDF](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md)
(if applicable)
- [x] I have performed a self-review of my own code
- [x] My changes generate no new warnings

### Documentation

- [ ] I have updated relevant docs on [Stirling-PDF's doc
repo](https://github.com/Stirling-Tools/Stirling-Tools.github.io/blob/main/docs/)
(if functionality has heavily changed)
- [ ] I have read the section [Add New Translation
Tags](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/HowToAddNewLanguage.md#add-new-translation-tags)
(for new translation tags only)

### UI Changes (if applicable)

- [ ] Screenshots or videos demonstrating the UI changes are attached
(e.g., as comments or direct attachments in the PR)

### Testing (if applicable)

- [x] I have tested my changes locally. Refer to the [Testing
Guide](https://github.com/Stirling-Tools/Stirling-PDF/blob/main/devGuide/DeveloperGuide.md#6-testing)
for more details.

---------

Signed-off-by: dependabot[bot] <[email protected]>
Signed-off-by: stirlingbot[bot] <stirlingbot[bot]@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Ludy <[email protected]>
Co-authored-by: EthanHealy01 <[email protected]>
Co-authored-by: Ethan <[email protected]>
Co-authored-by: Anthony Stirling <[email protected]>
Co-authored-by: stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
This commit is contained in:
Dario Ghunney Ware
2025-10-24 10:49:52 +01:00
committed by GitHub
co-authored by dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Ludy EthanHealy01 Ethan Anthony Stirling stirlingbot[bot] <195170888+stirlingbot[bot]@users.noreply.github.com>
parent c9eee00d66
commit 848ff9688b
65 changed files with 3991 additions and 288 deletions
@@ -1,6 +1,8 @@
package stirling.software.proprietary.security;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -38,7 +40,6 @@ class CustomLogoutSuccessHandlerTest {
when(response.isCommitted()).thenReturn(false);
when(jwtService.extractToken(request)).thenReturn(token);
doNothing().when(jwtService).clearToken(response);
when(request.getContextPath()).thenReturn("");
when(response.encodeRedirectURL(logoutPath)).thenReturn(logoutPath);
@@ -56,14 +57,12 @@ class CustomLogoutSuccessHandlerTest {
when(response.isCommitted()).thenReturn(false);
when(jwtService.extractToken(request)).thenReturn(token);
doNothing().when(jwtService).clearToken(response);
when(request.getContextPath()).thenReturn("");
when(response.encodeRedirectURL(logoutPath)).thenReturn(logoutPath);
customLogoutSuccessHandler.onLogoutSuccess(request, response, null);
verify(response).sendRedirect(logoutPath);
verify(jwtService).clearToken(response);
}
@Test
@@ -127,7 +127,6 @@ class JwtAuthenticationFilterTest {
.setAuthentication(any(UsernamePasswordAuthenticationToken.class));
verify(jwtService)
.generateToken(any(UsernamePasswordAuthenticationToken.class), eq(claims));
verify(jwtService).addToken(response, newToken);
verify(filterChain).doFilter(request, response);
}
}
@@ -8,8 +8,6 @@ import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.contains;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -17,7 +15,6 @@ import static org.mockito.Mockito.when;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
@@ -27,13 +24,10 @@ import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.Authentication;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@@ -59,7 +53,7 @@ class JwtServiceTest {
private JwtVerificationKey testVerificationKey;
@BeforeEach
void setUp() throws NoSuchAlgorithmException {
void setUp() throws Exception {
// Generate a test keypair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
@@ -224,7 +218,8 @@ class JwtServiceTest {
assertEquals("admin", extractedClaims.get("role"));
assertEquals("IT", extractedClaims.get("department"));
assertEquals(username, extractedClaims.get("sub"));
assertEquals("Stirling PDF", extractedClaims.get("iss"));
// Verify the constant issuer is set correctly
assertEquals("https://stirling.com", extractedClaims.get("iss"));
}
@Test
@@ -239,62 +234,27 @@ class JwtServiceTest {
}
@Test
void testExtractTokenWithCookie() {
void testExtractTokenWithAuthorizationHeader() {
String token = "test-token";
Cookie[] cookies = {new Cookie("stirling_jwt", token)};
when(request.getCookies()).thenReturn(cookies);
when(request.getHeader("Authorization")).thenReturn("Bearer " + token);
assertEquals(token, jwtService.extractToken(request));
}
@Test
void testExtractTokenWithNoCookies() {
when(request.getCookies()).thenReturn(null);
void testExtractTokenWithNoAuthorizationHeader() {
when(request.getHeader("Authorization")).thenReturn(null);
assertNull(jwtService.extractToken(request));
}
@Test
void testExtractTokenWithWrongCookie() {
Cookie[] cookies = {new Cookie("OTHER_COOKIE", "value")};
when(request.getCookies()).thenReturn(cookies);
void testExtractTokenWithInvalidAuthorizationHeaderFormat() {
when(request.getHeader("Authorization")).thenReturn("InvalidFormat token");
assertNull(jwtService.extractToken(request));
}
@Test
void testExtractTokenWithInvalidAuthorizationHeader() {
when(request.getCookies()).thenReturn(null);
assertNull(jwtService.extractToken(request));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void testAddToken(boolean secureCookie) throws Exception {
String token = "test-token";
// Create new JwtService instance with the secureCookie parameter
JwtService testJwtService = createJwtServiceWithSecureCookie(secureCookie);
testJwtService.addToken(response, token);
verify(response).addHeader(eq("Set-Cookie"), contains("stirling_jwt=" + token));
verify(response).addHeader(eq("Set-Cookie"), contains("HttpOnly"));
if (secureCookie) {
verify(response).addHeader(eq("Set-Cookie"), contains("Secure"));
}
}
@Test
void testClearToken() {
jwtService.clearToken(response);
verify(response).addHeader(eq("Set-Cookie"), contains("stirling_jwt="));
verify(response).addHeader(eq("Set-Cookie"), contains("Max-Age=0"));
}
@Test
void testGenerateTokenWithKeyId() throws Exception {
String username = "testuser";
@@ -373,17 +333,4 @@ class JwtServiceTest {
// Verify fallback logic was used
verify(keystoreService, atLeast(1)).getActiveKey();
}
private JwtService createJwtServiceWithSecureCookie(boolean secureCookie) throws Exception {
// Use reflection to create JwtService with custom secureCookie value
JwtService testService = new JwtService(true, keystoreService);
// Set the secureCookie field using reflection
java.lang.reflect.Field secureCookieField =
JwtService.class.getDeclaredField("secureCookie");
secureCookieField.setAccessible(true);
secureCookieField.set(testService, secureCookie);
return testService;
}
}