Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

Add opt-in redirectBaseUrl for OAuth2 and SAML behind reverse proxies (#8473)

Anthony Stirlingca02b5963de8
diff --git a/.github/aur/stirling-pdf-desktop/PKGBUILD b/.github/aur/stirling-pdf-desktop/PKGBUILD
index 4edabc522c..40e523e919 100644
--- a/.github/aur/stirling-pdf-desktop/PKGBUILD
+++ b/.github/aur/stirling-pdf-desktop/PKGBUILD
@@ -1,6 +1,6 @@
# Maintainer: Stirling PDF Inc <[email protected]>
pkgname=stirling-pdf-desktop
-pkgver=3.1.0
+pkgver=3.2.0
pkgrel=1
pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"
arch=('x86_64')
diff --git a/.github/aur/stirling-pdf-server-bin/PKGBUILD b/.github/aur/stirling-pdf-server-bin/PKGBUILD
index 2b6e4c923e..626810da44 100644
--- a/.github/aur/stirling-pdf-server-bin/PKGBUILD
+++ b/.github/aur/stirling-pdf-server-bin/PKGBUILD
@@ -1,6 +1,6 @@
# Maintainer: Stirling PDF Inc <[email protected]>
pkgname=stirling-pdf-server-bin
-pkgver=3.1.0
+pkgver=3.2.0
pkgrel=1
pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"
arch=('any')
diff --git a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
index f53afbde3a..fba98cf2c1 100644
--- a/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
+++ b/app/common/src/main/java/stirling/software/common/model/ApplicationProperties.java
@@ -1044,6 +1044,9 @@ public class ApplicationProperties {
private Boolean blockRegistration = false;
private String registrationId = "stirling";
+ // Opt-in public URL for SAML endpoints; wins over system.backendUrl when set.
+ private String redirectBaseUrl;
+
@ToString.Exclude
@JsonProperty("idpMetadataUri")
private String idpMetadataUri;
@@ -1124,6 +1127,9 @@ public class ApplicationProperties {
private String provider;
private Client client = new Client();
+ // Opt-in public URL for OAuth2 callbacks; blank keeps building them from each request.
+ private String redirectBaseUrl;
+
/**
* When true, the OAuth2/OIDC login flow logs the full set of ID token and UserInfo
* claims at INFO level (and again at ERROR level if the username attribute cannot be
diff --git a/app/core/src/main/resources/settings.yml.template b/app/core/src/main/resources/settings.yml.template
index 0e1e0bf74f..bf0f9c9752 100644
--- a/app/core/src/main/resources/settings.yml.template
+++ b/app/core/src/main/resources/settings.yml.template
@@ -47,12 +47,14 @@ security:
useAsUsername: email # default is 'email'; custom fields can be used as the username
scopes: openid, profile, email # specify the scopes for which the application will request permissions
provider: google # set this to your OAuth Provider's name, e.g., 'google' or 'keycloak'
+ redirectBaseUrl: "" # optional public URL users open Stirling-PDF at, e.g. 'https://pdf.example.com' (include any context path). Set it when a reverse proxy (e.g. Azure App Proxy) hides https or the public host, so OAuth callbacks become <redirectBaseUrl>/login/oauth2/code/<provider>. Leave blank to build them from each request
saml2:
enabled: false # Only enabled for paid enterprise clients (enterpriseEdition.enabled must be true)
provider: "" # The name of your Provider
autoCreateUser: true # set to 'true' to allow auto-creation of non-existing users
blockRegistration: false # set to 'true' to deny login with SSO without prior registration by an admin
registrationId: stirling # The name of your Service Provider (SP) app name. Should match the name in the path for your SSO & SLO URLs
+ redirectBaseUrl: "" # optional public URL users open Stirling-PDF at, e.g. 'https://pdf.example.com' (include any context path). Overrides system.backendUrl for the SAML entity ID, ACS and logout URLs. Leave blank to use system.backendUrl
idpMetadataUri: https://dev-XXXXXXXX.okta.com/app/externalKey/sso/saml/metadata # The uri for your Provider's metadata
idpSingleLoginUrl: https://dev-XXXXXXXX.okta.com/app/dev-XXXXXXXX_stirlingpdf_1/externalKey/sso/saml # The URL for initiating SSO. Provided by your Provider
idpSingleLogoutUrl: https://dev-XXXXXXXX.okta.com/app/dev-XXXXXXXX_stirlingpdf_1/externalKey/slo/saml # The URL for initiating SLO. Provided by your Provider
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
index f6f309f2c7..30a3b55509 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/controller/api/ProprietaryUIDataController.java
@@ -56,6 +56,7 @@ import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.MfaService;
import stirling.software.proprietary.security.service.TeamService;
import stirling.software.proprietary.security.session.SessionPersistentRegistry;
+import stirling.software.proprietary.security.util.RedirectBaseUrl;
import stirling.software.proprietary.service.UserLicenseSettingsService;
import tools.jackson.core.JacksonException;
@@ -121,19 +122,14 @@ public class ProprietaryUIDataController {
}
/**
- * Get the backend base URL for SAML/OAuth redirects. Uses system.backendUrl from config if set,
- * otherwise defaults to http://localhost:8080
+ * Base URL for the SAML login link: security.saml2.redirectBaseUrl, then system.backendUrl,
+ * then http://localhost:8080 for development.
*/
private String getBackendBaseUrl() {
- String backendUrl = applicationProperties.getSystem().getBackendUrl();
-
- // If backendUrl is configured, use it
- if (backendUrl != null && !backendUrl.trim().isEmpty()) {
- return backendUrl.trim();
- }
-
- // For development, default to localhost:8080 (backend port)
- return "http://localhost:8080";
+ return RedirectBaseUrl.overrideOr(
+ applicationProperties.getSecurity().getSaml2().getRedirectBaseUrl(),
+ applicationProperties.getSystem().getBackendUrl())
+ .orElse("http://localhost:8080");
}
@GetMapping("/audit-dashboard")
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/CustomLogoutSuccessHandler.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/CustomLogoutSuccessHandler.java
index d83b684166..bbb94b1638 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/CustomLogoutSuccessHandler.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/CustomLogoutSuccessHandler.java
@@ -25,7 +25,6 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
-import stirling.software.common.configuration.AppConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.ApplicationProperties.Security.OAUTH2;
import stirling.software.common.model.ApplicationProperties.Security.SAML2;
@@ -38,6 +37,7 @@ import stirling.software.proprietary.audit.Audited;
import stirling.software.proprietary.security.saml2.CertificateUtils;
import stirling.software.proprietary.security.saml2.CustomSaml2AuthenticatedPrincipal;
import stirling.software.proprietary.security.service.JwtServiceInterface;
+import stirling.software.proprietary.security.util.RedirectBaseUrl;
import stirling.software.proprietary.service.AiUserDataService;
@Slf4j
@@ -48,12 +48,12 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
private final ApplicationProperties.Security securityProperties;
- private final AppConfig appConfig;
-
private final JwtServiceInterface jwtService;
private final AiUserDataService aiUserDataService;
+ private final ApplicationProperties applicationProperties;
+
private static final AuthenticationTrustResolver TRUST_RESOLVER =
new AuthenticationTrustResolverImpl();
@@ -147,7 +147,7 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
certificates.add(certificate);
// Construct URLs required for SAML configuration
- SamlClient samlClient = getSamlClient(registrationId, samlConf, certificates);
+ SamlClient samlClient = getSamlClient(request, registrationId, samlConf, certificates);
// Read private key for service provider
Resource privateKeyResource = samlConf.getPrivateKey();
@@ -158,7 +158,11 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
// Build relay state to return user to login page after IdP logout
String relayState =
- UrlUtils.getOrigin(request) + request.getContextPath() + LOGOUT_PATH;
+ RedirectBaseUrl.landingBase(
+ samlConf.getRedirectBaseUrl(),
+ applicationProperties.getSystem().getFrontendUrl())
+ .orElseGet(() -> UrlUtils.getOrigin(request))
+ + LOGOUT_PATH;
// Redirect to identity provider for logout with relay state
samlClient.redirectToIdentityProvider(response, relayState, nameIdValue);
@@ -182,7 +186,12 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
OAUTH2 oauth = securityProperties.getOauth2();
String path = checkForErrors(request);
- String redirectUrl = UrlUtils.getOrigin(request) + "/login?" + path;
+ String baseUrl =
+ RedirectBaseUrl.landingBase(
+ oauth.getRedirectBaseUrl(),
+ applicationProperties.getSystem().getFrontendUrl())
+ .orElseGet(() -> UrlUtils.getOrigin(request));
+ String redirectUrl = baseUrl + "/login?" + path;
registrationId = oAuthToken.getAuthorizedClientRegistrationId();
// Redirect based on OAuth2 provider
@@ -232,9 +241,17 @@ public class CustomLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {
}
private SamlClient getSamlClient(
- String registrationId, SAML2 samlConf, List<X509Certificate> certificates)
+ HttpServletRequest request,
+ String registrationId,
+ SAML2 samlConf,
+ List<X509Certificate> certificates)
throws SamlException {
- String serverUrl = appConfig.getBackendUrl() + ":" + appConfig.getServerPort();
+ // Must match the entity ID and ACS URL that Saml2Configuration publishes.
+ String serverUrl =
+ RedirectBaseUrl.overrideOr(
+ samlConf.getRedirectBaseUrl(),
+ applicationProperties.getSystem().getBackendUrl())
+ .orElseGet(() -> UrlUtils.getOrigin(request));
String relyingPartyIdentifier =
serverUrl + "/saml2/service-provider-metadata/" + registrationId;
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java
index d49e365474..f7b6e465b8 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/configuration/SecurityConfiguration.java
@@ -39,7 +39,6 @@ import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import lombok.extern.slf4j.Slf4j;
-import stirling.software.common.configuration.AppConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.util.RequestUriUtils;
import stirling.software.proprietary.security.CustomAuthenticationFailureHandler;
@@ -80,7 +79,6 @@ public class SecurityConfiguration {
private final ApplicationProperties applicationProperties;
private final ApplicationProperties.Security securityProperties;
- private final AppConfig appConfig;
private final UserAuthenticationFilter userAuthenticationFilter;
private final JwtServiceInterface jwtService;
private final JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@@ -102,7 +100,6 @@ public class SecurityConfiguration {
@Lazy UserService userService,
@Qualifier("loginEnabled") boolean loginEnabledValue,
@Qualifier("runningProOrHigher") boolean runningProOrHigher,
- AppConfig appConfig,
ApplicationProperties applicationProperties,
ApplicationProperties.Security securityProperties,
UserAuthenticationFilter userAuthenticationFilter,
@@ -123,7 +120,6 @@ public class SecurityConfiguration {
this.userService = userService;
this.loginEnabledValue = loginEnabledValue;
this.runningProOrHigher = runningProOrHigher;
- this.appConfig = appConfig;
this.applicationProperties = applicationProperties;
this.securityProperties = securityProperties;
this.userAuthenticationFilter = userAuthenticationFilter;
@@ -331,9 +327,9 @@ public class SecurityConfiguration {
.logoutSuccessHandler(
new CustomLogoutSuccessHandler(
securityProperties,
- appConfig,
jwtService,
- aiUserDataService))
+ aiUserDataService,
+ applicationProperties))
.clearAuthentication(true)
.invalidateHttpSession(true)
.deleteCookies("JSESSIONID", "remember-me", "stirling_jwt"));
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java
index 5778157cd9..94b7421dae 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandler.java
@@ -37,6 +37,7 @@ import stirling.software.proprietary.security.service.JwtServiceInterface;
import stirling.software.proprietary.security.service.LoginAttemptService;
import stirling.software.proprietary.security.service.UserService;
import stirling.software.proprietary.security.util.DesktopClientUtils;
+import stirling.software.proprietary.security.util.RedirectBaseUrl;
@Slf4j
@RequiredArgsConstructor
@@ -194,13 +195,22 @@ public class CustomOAuth2AuthenticationSuccessHandler
HttpServletResponse response,
String contextPath,
String jwt) {
- String redirectPath = resolveRedirectPath(request, contextPath);
+ Optional<String> landingBase =
+ RedirectBaseUrl.landingBase(
+ oauth2Properties.getRedirectBaseUrl(),
+ applicationProperties.getSystem().getFrontendUrl());
+ // The SPA cookie path already includes the browser-side base path, so only add an origin.
+ boolean usesCookiePath =
+ !TauriOAuthUtils.isTauriState(request) && cookieRedirectPath(request) != null;
+ String pathPrefix = landingBase.isPresent() && !usesCookiePath ? "" : contextPath;
+ String redirectPath = resolveRedirectPath(request, pathPrefix);
+ Optional<String> configuredBase =
+ usesCookiePath ? landingBase.flatMap(RedirectBaseUrl::origin) : landingBase;
String origin =
- resolveForwardedOrigin(request)
- .orElseGet(
- () ->
- resolveOriginFromReferer(request)
- .orElseGet(() -> buildOriginFromRequest(request)));
+ configuredBase
+ .or(() -> resolveForwardedOrigin(request))
+ .or(() -> resolveOriginFromReferer(request))
+ .orElseGet(() -> buildOriginFromRequest(request));
clearRedirectCookie(response);
// Extract nonce from state for CSRF validation in callback
@@ -219,11 +229,13 @@ public class CustomOAuth2AuthenticationSuccessHandler
if (TauriOAuthUtils.isTauriState(request)) {
return TauriOAuthUtils.defaultTauriCallbackPath(contextPath);
}
+ String cookiePath = cookieRedirectPath(request);
+ return cookiePath != null ? cookiePath : TauriOAuthUtils.defaultCallbackPath(contextPath);
+ }
+
+ private String cookieRedirectPath(HttpServletRequest request) {
String cookiePath = TauriOAuthUtils.extractRedirectPathFromCookie(request);
- if (cookiePath != null && cookiePath.startsWith("/")) {
- return cookiePath;
- }
- return TauriOAuthUtils.defaultCallbackPath(contextPath);
+ return cookiePath != null && cookiePath.startsWith("/") ? cookiePath : null;
}
private Optional<String> resolveForwardedOrigin(HttpServletRequest request) {
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/OAuth2Configuration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/OAuth2Configuration.java
index 8710ed2641..31af756bbf 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/OAuth2Configuration.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/oauth2/OAuth2Configuration.java
@@ -38,13 +38,15 @@ import stirling.software.proprietary.security.model.Authority;
import stirling.software.proprietary.security.model.User;
import stirling.software.proprietary.security.model.exception.NoProviderFoundException;
import stirling.software.proprietary.security.service.UserService;
+import stirling.software.proprietary.security.util.RedirectBaseUrl;
@Slf4j
@Configuration
@ConditionalOnProperty(prefix = "security", name = "oauth2.enabled", havingValue = "true")
public class OAuth2Configuration {
- public static final String REDIRECT_URI_PATH = "{baseUrl}/login/oauth2/code/";
+ private static final String CALLBACK_PATH = "/login/oauth2/code/";
+ public static final String REDIRECT_URI_PATH = "{baseUrl}" + CALLBACK_PATH;
private final ApplicationProperties applicationProperties;
@Lazy private final UserService userService;
@@ -61,6 +63,7 @@ public class OAuth2Configuration {
@Bean
public ClientRegistrationRepository clientRegistrationRepository()
throws NoProviderFoundException {
+ logRedirectBaseUrl();
List<ClientRegistration> registrations = new ArrayList<>();
githubClientRegistration().ifPresent(registrations::add);
oidcClientRegistration().ifPresent(registrations::add);
@@ -106,6 +109,7 @@ public class OAuth2Configuration {
.scope(keycloak.getScopes())
.userNameAttributeName(keycloak.getUseAsUsername().getName())
.clientName(keycloak.getClientName())
+ .redirectUri(redirectUri(keycloak.getName()))
.build())
: Optional.empty();
}
@@ -137,7 +141,7 @@ public class OAuth2Configuration {
.userInfoUri(google.getUserInfoUri())
.userNameAttributeName(google.getUseAsUsername().getName())
.clientName(google.getClientName())
- .redirectUri(REDIRECT_URI_PATH + google.getName())
+ .redirectUri(redirectUri(google.getName()))
.authorizationGrantType(AUTHORIZATION_CODE)
.build())
: Optional.empty();
@@ -183,7 +187,7 @@ public class OAuth2Configuration {
.userInfoUri(github.getUserInfoUri())
.userNameAttributeName(github.getUseAsUsername().getName())
.clientName(github.getClientName())
- .redirectUri(REDIRECT_URI_PATH + github.getName())
+ .redirectUri(redirectUri(github.getName()))
.authorizationGrantType(AUTHORIZATION_CODE)
.build())
: Optional.empty();
@@ -221,7 +225,7 @@ public class OAuth2Configuration {
"Initialised OIDC OAuth2 provider: registrationId='{}', issuer='{}', redirectUri='{}'",
name,
oauth.getIssuer(),
- REDIRECT_URI_PATH + name);
+ redirectUri(name));
} else {
log.warn("OIDC OAuth2 provider validation failed - provider will not be registered");
}
@@ -235,12 +239,35 @@ public class OAuth2Configuration {
.scope(oidcProvider.getScopes())
.userNameAttributeName(oidcProvider.getUseAsUsername().getName())
.clientName(clientName)
- .redirectUri(REDIRECT_URI_PATH + name)
+ .redirectUri(redirectUri(name))
.authorizationGrantType(AUTHORIZATION_CODE)
.build())
: Optional.empty();
}
+ private String redirectUri(String registrationId) {
+ return RedirectBaseUrl.parse(
+ applicationProperties.getSecurity().getOauth2().getRedirectBaseUrl())
+ .map(base -> base + CALLBACK_PATH + registrationId)
+ .orElse(REDIRECT_URI_PATH + registrationId);
+ }
+
+ private void logRedirectBaseUrl() {
+ String configured = applicationProperties.getSecurity().getOauth2().getRedirectBaseUrl();
+ if (isStringEmpty(configured)) {
+ return;
+ }
+ RedirectBaseUrl.parse(configured)
+ .ifPresentOrElse(
+ base -> log.info("OAuth2 callback URLs pinned to {}", base),
+ () ->
+ log.error(
+ "Ignoring security.oauth2.redirectBaseUrl '{}': expected an"
+ + " absolute http(s) URL such as"
+ + " https://pdf.example.com",
+ configured));
+ }
+
private boolean isOAuth2Disabled(OAUTH2 oAuth2) {
return oAuth2 == null || !oAuth2.getEnabled();
}
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/Saml2Configuration.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/Saml2Configuration.java
index f42fc562d8..c3eec8cfe5 100644
--- a/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/Saml2Configuration.java
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/saml2/Saml2Configuration.java
@@ -1,5 +1,7 @@
package stirling.software.proprietary.security.saml2;
+import static stirling.software.common.util.ValidationUtils.isStringEmpty;
+
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.UUID;
@@ -24,6 +26,7 @@ import lombok.extern.slf4j.Slf4j;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.common.model.ApplicationProperties.Security.SAML2;
+import stirling.software.proprietary.security.util.RedirectBaseUrl;
@Configuration
@Slf4j
@@ -99,14 +102,23 @@ public class Saml2Configuration {
throw new IllegalStateException("Failed to load SAML2 SP credentials", e);
}
- // Get backend URL from configuration (for SAML endpoints)
- String backendUrl = applicationProperties.getSystem().getBackendUrl();
- if (backendUrl == null || backendUrl.isBlank()) {
+ String override = samlConf.getRedirectBaseUrl();
+ if (!isStringEmpty(override) && RedirectBaseUrl.parse(override).isEmpty()) {
+ log.error(
+ "Ignoring security.saml2.redirectBaseUrl '{}': expected an absolute http(s) URL"
+ + " such as https://pdf.example.com",
+ override);
+ }
+ String backendUrl =
+ RedirectBaseUrl.overrideOr(
+ override, applicationProperties.getSystem().getBackendUrl())
+ .orElse(null);
+ if (backendUrl == null) {
backendUrl = "{baseUrl}"; // Fallback to Spring's auto-resolution
log.warn(
"system.backendUrl not configured - SAML metadata will use request-based URLs. Set system.backendUrl for production use.");
} else {
- log.info("Using configured backend URL for SAML: {}", backendUrl);
+ log.info("Using configured base URL for SAML: {}", backendUrl);
}
String entityId =
diff --git a/app/proprietary/src/main/java/stirling/software/proprietary/security/util/RedirectBaseUrl.java b/app/proprietary/src/main/java/stirling/software/proprietary/security/util/RedirectBaseUrl.java
new file mode 100644
index 0000000000..2ed0187602
--- /dev/null
+++ b/app/proprietary/src/main/java/stirling/software/proprietary/security/util/RedirectBaseUrl.java
@@ -0,0 +1,66 @@
+package stirling.software.proprietary.security.util;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.regex.Pattern;
+
+/** Parses the opt-in {@code redirectBaseUrl} settings: public URLs that replace {baseUrl}. */
+public final class RedirectBaseUrl {
+
+ private static final Pattern TRAILING_SLASHES = Pattern.compile("/+$");
+
+ private RedirectBaseUrl() {}
+
+ /** Empty when unset or not an absolute http(s) URL without query, fragment or user info. */
+ public static Optional<String> parse(String value) {
+ if (value == null || value.isBlank()) {
+ return Optional.empty();
+ }
+ String trimmed = TRAILING_SLASHES.matcher(value.trim()).replaceAll("");
+ try {
+ URI uri = new URI(trimmed);
+ String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT);
+ boolean valid =
+ ("http".equals(scheme) || "https".equals(scheme))
+ && uri.getHost() != null
+ && uri.getRawUserInfo() == null
+ && uri.getRawQuery() == null
+ && uri.getRawFragment() == null;
+ return valid ? Optional.of(trimmed) : Optional.empty();
+ } catch (URISyntaxException e) {
+ return Optional.empty();
+ }
+ }
+
+ /** Scheme and authority of a URL, e.g. {@code https://pdf.example.com}. */
+ public static Optional<String> origin(String value) {
+ return parse(value)
+ .map(URI::create)
+ .map(uri -> uri.getScheme() + "://" + uri.getRawAuthority());
+ }
+
+ /** Override first, then a non-blank fallback setting with trailing slashes removed. */
+ public static Optional<String> overrideOr(String override, String fallback) {
+ return parse(override)
+ .or(
+ () ->
+ Optional.ofNullable(fallback)
+ .map(String::trim)
+ .filter(value -> !value.isEmpty())
+ .map(
+ value ->
+ TRAILING_SLASHES
+ .matcher(value)
+ .replaceAll("")));
+ }
+
+ /**
+ * Where users land after login or logout once an override is set: the frontend URL when the UI
+ * is hosted apart from the backend, else the override. Empty when no override is set.
+ */
+ public static Optional<String> landingBase(String override, String frontendUrl) {
+ return parse(override).map(base -> parse(frontendUrl).orElse(base));
+ }
+}
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/CustomLogoutSuccessHandlerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/CustomLogoutSuccessHandlerTest.java
index c4ae42f578..3a4ead44d5 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/CustomLogoutSuccessHandlerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/CustomLogoutSuccessHandlerTest.java
@@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
+import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
@@ -26,6 +27,8 @@ class CustomLogoutSuccessHandlerTest {
@Mock private JwtServiceInterface jwtService;
+ @Spy private ApplicationProperties applicationProperties = new ApplicationProperties();
+
@InjectMocks private CustomLogoutSuccessHandler customLogoutSuccessHandler;
@Test
@@ -85,6 +88,45 @@ class CustomLogoutSuccessHandlerTest {
verify(response).sendRedirect("http://localhost:8080/login?logout=true");
}
+ @Test
+ void oauth2LogoutUsesRedirectBaseUrlWhenSet() throws IOException {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpServletResponse response = mock(HttpServletResponse.class);
+ OAuth2AuthenticationToken oAuth2AuthenticationToken = mock(OAuth2AuthenticationToken.class);
+ ApplicationProperties.Security.OAUTH2 oauth =
+ mock(ApplicationProperties.Security.OAUTH2.class);
+
+ when(response.isCommitted()).thenReturn(false);
+ when(request.getParameter("oAuth2AuthenticationErrorWeb")).thenReturn(null);
+ when(request.getParameter("errorOAuth")).thenReturn(null);
+ when(securityProperties.getOauth2()).thenReturn(oauth);
+ when(oauth.getRedirectBaseUrl()).thenReturn("https://pdf.example.com/");
+ when(oAuth2AuthenticationToken.getAuthorizedClientRegistrationId()).thenReturn("Microsoft");
+
+ customLogoutSuccessHandler.onLogoutSuccess(request, response, oAuth2AuthenticationToken);
+
+ verify(response).sendRedirect("https://pdf.example.com/login?logout=true");
+ }
+
+ @Test
+ void oauth2LogoutLandsOnSeparateFrontendWhenRedirectBaseUrlSet() throws IOException {
+ HttpServletRequest request = mock(HttpServletRequest.class);
+ HttpServletResponse response = mock(HttpServletResponse.class);
+ OAuth2AuthenticationToken oAuth2AuthenticationToken = mock(OAuth2AuthenticationToken.class);
+ ApplicationProperties.Security.OAUTH2 oauth =
+ mock(ApplicationProperties.Security.OAUTH2.class);
+ applicationProperties.getSystem().setFrontendUrl("https://app.example.com");
+
+ when(response.isCommitted()).thenReturn(false);
+ when(securityProperties.getOauth2()).thenReturn(oauth);
+ when(oauth.getRedirectBaseUrl()).thenReturn("https://api.example.com");
+ when(oAuth2AuthenticationToken.getAuthorizedClientRegistrationId()).thenReturn("Microsoft");
+
+ customLogoutSuccessHandler.onLogoutSuccess(request, response, oAuth2AuthenticationToken);
+
+ verify(response).sendRedirect("https://app.example.com/login?logout=true");
+ }
+
@Test
void testUserIsDisabledRedirect() throws IOException {
String error = "userIsDisabled";
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/SecurityConfigurationTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/SecurityConfigurationTest.java
index fe2bf8e948..2a977a31e8 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/SecurityConfigurationTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/configuration/SecurityConfigurationTest.java
@@ -22,7 +22,6 @@ import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
-import stirling.software.common.configuration.AppConfig;
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.security.JwtAuthenticationEntryPoint;
import stirling.software.proprietary.security.database.repository.PersistentLoginRepository;
@@ -48,7 +47,6 @@ class SecurityConfigurationTest {
private CustomUserDetailsService userDetailsService;
private UserService userService;
- private AppConfig appConfig;
private UserAuthenticationFilter userAuthenticationFilter;
private JwtServiceInterface jwtService;
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@@ -69,7 +67,6 @@ class SecurityConfigurationTest {
userService,
loginEnabled,
true,
- appConfig,
applicationProperties,
securityProperties,
userAuthenticationFilter,
@@ -90,7 +87,6 @@ class SecurityConfigurationTest {
void setUp() {
userDetailsService = mock(CustomUserDetailsService.class);
userService = mock(UserService.class);
- appConfig = mock(AppConfig.class);
userAuthenticationFilter = mock(UserAuthenticationFilter.class);
jwtService = mock(JwtServiceInterface.class);
jwtAuthenticationEntryPoint = mock(JwtAuthenticationEntryPoint.class);
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java
index 009d7c0ab5..df942fd09c 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/CustomOAuth2AuthenticationSuccessHandlerTest.java
@@ -27,6 +27,8 @@ import org.springframework.security.oauth2.client.authentication.OAuth2Authentic
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.web.savedrequest.SavedRequest;
+import jakarta.servlet.http.Cookie;
+
import stirling.software.common.model.ApplicationProperties;
import stirling.software.proprietary.accountlink.EntitlementCache;
import stirling.software.proprietary.model.UserLicenseSettings;
@@ -99,6 +101,74 @@ class CustomOAuth2AuthenticationSuccessHandlerTest {
response.getRedirectedUrl());
}
+ @ParameterizedTest
+ @CsvSource(
+ value = {
+ "'', '', '', http://hcrn-fs01:8080/auth/callback#access_token=jwt",
+ "'', https://app.example.com, '',"
+ + " http://hcrn-fs01:8080/auth/callback#access_token=jwt",
+ "https://pdf.example.com/, '', '',"
+ + " https://pdf.example.com/auth/callback#access_token=jwt",
+ "https://api.example.com, https://app.example.com/, '',"
+ + " https://app.example.com/auth/callback#access_token=jwt",
+ "https://example.com/pdf, '', '',"
+ + " https://example.com/pdf/auth/callback#access_token=jwt",
+ "https://example.com/pdf, '', /pdf/auth/callback,"
+ + " https://example.com/pdf/auth/callback#access_token=jwt"
+ },
+ emptyValue = "")
+ void postLoginRedirectUsesRedirectBaseUrlWhenSet(
+ String redirectBaseUrl, String frontendUrl, String cookiePath, String expected)
+ throws Exception {
+ UserService userService = mock(UserService.class);
+ JwtServiceInterface jwtService = mock(JwtServiceInterface.class);
+ ApplicationProperties applicationProperties = new ApplicationProperties();
+ ApplicationProperties.Security.OAUTH2 oauth2Props =
+ applicationProperties.getSecurity().getOauth2();
+ oauth2Props.setRedirectBaseUrl(redirectBaseUrl);
+ applicationProperties.getSystem().setFrontendUrl(frontendUrl);
+
+ CustomOAuth2AuthenticationSuccessHandler handler =
+ new CustomOAuth2AuthenticationSuccessHandler(
+ mock(LoginAttemptService.class),
+ oauth2Props,
+ userService,
+ jwtService,
+ mock(UserLicenseSettingsService.class),
+ applicationProperties);
+
+ when(userService.usernameExistsIgnoreCase("user")).thenReturn(false);
+ when(userService.isUserDisabled("user")).thenReturn(false);
+ when(jwtService.isJwtEnabled()).thenReturn(true);
+ when(jwtService.generateToken(
+ any(org.springframework.security.core.Authentication.class),
+ org.mockito.Mockito.anyMap()))
+ .thenReturn("jwt");
+
+ DefaultOAuth2User oauthUser =
+ new DefaultOAuth2User(
+ List.of(new SimpleGrantedAuthority("ROLE_USER")),
+ Map.of("sub", "provider-sub", "name", "user"),
+ "name");
+ OAuth2AuthenticationToken authentication =
+ new OAuth2AuthenticationToken(oauthUser, oauthUser.getAuthorities(), "Microsoft");
+
+ // What Stirling sees behind a TLS-terminating proxy that sends no X-Forwarded-* headers.
+ MockHttpServletRequest request = new MockHttpServletRequest();
+ request.setContextPath("");
+ request.setScheme("http");
+ request.setServerName("hcrn-fs01");
+ request.setServerPort(8080);
+ if (!cookiePath.isEmpty()) {
+ request.setCookies(new Cookie(TauriOAuthUtils.SPA_REDIRECT_COOKIE, cookiePath));
+ }
+ MockHttpServletResponse response = new MockHttpServletResponse();
+
+ handler.onAuthenticationSuccess(request, response, authentication);
+
+ assertEquals(expected, response.getRedirectedUrl());
+ }
+
@ParameterizedTest
@CsvSource({
"NORMAL, 4, false, false, true",
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2ConfigurationMoreTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2ConfigurationMoreTest.java
index 4ce7ba523d..a3b92dd661 100644
--- a/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2ConfigurationMoreTest.java
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/oauth2/OAuth2ConfigurationMoreTest.java
@@ -109,6 +109,51 @@ class OAuth2ConfigurationMoreTest {
}
}
+ @Nested
+ @DisplayName("redirectBaseUrl")
+ class RedirectBaseUrl {
+
+ private String githubRedirectUri(String redirectBaseUrl) throws NoProviderFoundException {
+ ApplicationProperties props = enabledProps();
+ OAUTH2 oauth2 = props.getSecurity().getOauth2();
+ oauth2.getClient().getGithub().setClientId("gh-id");
+ oauth2.getClient().getGithub().setClientSecret("gh-secret");
+ oauth2.setRedirectBaseUrl(redirectBaseUrl);
+ return newConfig(props)
+ .clientRegistrationRepository()
+ .findByRegistrationId("github")
+ .getRedirectUri();
+ }
+
+ @Test
+ @DisplayName("unset keeps the request-derived {baseUrl} template")
+ void unsetKeepsBaseUrlTemplate() throws NoProviderFoundException {
+ assertThat(githubRedirectUri(null)).isEqualTo("{baseUrl}/login/oauth2/code/github");
+ assertThat(githubRedirectUri(" ")).isEqualTo("{baseUrl}/login/oauth2/code/github");
+ }
+
+ @Test
+ @DisplayName("pins the callback to the configured public URL")
+ void pinsCallbackToPublicUrl() throws NoProviderFoundException {
+ assertThat(githubRedirectUri("https://pdf.example.com/"))
+ .isEqualTo("https://pdf.example.com/login/oauth2/code/github");
+ }
+
+ @Test
+ @DisplayName("keeps a context path in the configured public URL")
+ void keepsContextPath() throws NoProviderFoundException {
+ assertThat(githubRedirectUri("https://example.com/pdf"))
+ .isEqualTo("https://example.com/pdf/login/oauth2/code/github");
+ }
+
+ @Test
+ @DisplayName("ignores a value that is not an absolute http(s) URL")
+ void ignoresInvalidValue() throws NoProviderFoundException {
+ assertThat(githubRedirectUri("pdf.example.com"))
+ .isEqualTo("{baseUrl}/login/oauth2/code/github");
+ }
+ }
+
@Nested
@DisplayName("userAuthoritiesMapper")
class AuthoritiesMapper {
diff --git a/app/proprietary/src/test/java/stirling/software/proprietary/security/util/RedirectBaseUrlTest.java b/app/proprietary/src/test/java/stirling/software/proprietary/security/util/RedirectBaseUrlTest.java
new file mode 100644
index 0000000000..3bc74e8f9d
--- /dev/null
+++ b/app/proprietary/src/test/java/stirling/software/proprietary/security/util/RedirectBaseUrlTest.java
@@ -0,0 +1,73 @@
+package stirling.software.proprietary.security.util;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.NullAndEmptySource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class RedirectBaseUrlTest {
+
+ @ParameterizedTest
+ @CsvSource({
+ "https://pdf.example.com, https://pdf.example.com",
+ "https://pdf.example.com///, https://pdf.example.com",
+ "' https://pdf.example.com/ ', https://pdf.example.com",
+ "http://10.0.0.5:8080, http://10.0.0.5:8080",
+ "HTTPS://pdf.example.com/sub/, HTTPS://pdf.example.com/sub"
+ })
+ void normalisesValidUrls(String input, String expected) {
+ assertThat(RedirectBaseUrl.parse(input)).contains(expected);
+ }
+
+ @ParameterizedTest
+ @NullAndEmptySource
+ @ValueSource(
+ strings = {
+ " ",
+ "pdf.example.com",
+ "/relative",
+ "ftp://pdf.example.com",
+ "https://pdf.example.com?x=1",
+ "https://pdf.example.com#frag",
+ "https://user:[email protected]",
+ "https://bad host"
+ })
+ void rejectsUnusableValues(String input) {
+ assertThat(RedirectBaseUrl.parse(input)).isEmpty();
+ }
+
+ @ParameterizedTest
+ @CsvSource(
+ value = {
+ "https://public.example/, http://localhost, https://public.example",
+ "'', 'http://10.0.0.5:8080/ ', http://10.0.0.5:8080",
+ "not-a-url, http://10.0.0.5, http://10.0.0.5",
+ },
+ emptyValue = "")
+ void overrideWinsOverFallbackSetting(String override, String fallback, String expected) {
+ assertThat(RedirectBaseUrl.overrideOr(override, fallback)).contains(expected);
+ }
+
+ @Test
+ void overrideOrIsEmptyWhenNothingIsConfigured() {
+ assertThat(RedirectBaseUrl.overrideOr(null, " ")).isEmpty();
+ }
+
+ @Test
+ void landingBaseNeedsAnOverrideAndPrefersTheFrontend() {
+ assertThat(RedirectBaseUrl.landingBase(null, "https://app.example")).isEmpty();
+ assertThat(RedirectBaseUrl.landingBase("https://api.example", null))
+ .contains("https://api.example");
+ assertThat(RedirectBaseUrl.landingBase("https://api.example", "https://app.example/"))
+ .contains("https://app.example");
+ }
+
+ @Test
+ void originDropsThePath() {
+ assertThat(RedirectBaseUrl.origin("https://example.com:8443/pdf/"))
+ .contains("https://example.com:8443");
+ }
+}
diff --git a/build.gradle b/build.gradle
index ac9d47cee9..df61c54d68 100644
--- a/build.gradle
+++ b/build.gradle
@@ -122,7 +122,7 @@ springBoot {
allprojects {
group = 'stirling.software'
- version = '3.1.0'
+ version = '3.2.0'
configurations.configureEach {
exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"
diff --git a/frontend/editor/src-tauri/tauri.conf.json b/frontend/editor/src-tauri/tauri.conf.json
index ede029780a..acbd8bf980 100644
--- a/frontend/editor/src-tauri/tauri.conf.json
+++ b/frontend/editor/src-tauri/tauri.conf.json
@@ -2,7 +2,7 @@
"$schema": "../../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Stirling PDF",
"mainBinaryName": "Stirling-PDF",
- "version": "3.1.0",
+ "version": "3.2.0",
"identifier": "stirling.pdf.dev",
"build": {
"frontendDist": "../dist",
diff --git a/frontend/editor/src/core/testing/serverExperienceSimulations.ts b/frontend/editor/src/core/testing/serverExperienceSimulations.ts
index 1d7671cd15..39f855d65e 100644
--- a/frontend/editor/src/core/testing/serverExperienceSimulations.ts
+++ b/frontend/editor/src/core/testing/serverExperienceSimulations.ts
@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
- appVersion: "3.1.0",
+ appVersion: "3.2.0",
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
serverPort: 8080,
diff --git a/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts b/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts
index b3045c0444..a48554f771 100644
--- a/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts
+++ b/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts
@@ -48,7 +48,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {
const BASE_NO_LOGIN_CONFIG: AppConfig = {
enableAnalytics: true,
- appVersion: "3.1.0",
+ appVersion: "3.2.0",
serverCertificateEnabled: false,
enableAlphaFunctionality: false,
enableDesktopInstallSlide: true,