From 3f2816f745db6327d2779bc054228282038c54a5 Mon Sep 17 00:00:00 2001 From: Josh Cummings Date: Fri, 10 Mar 2023 10:42:37 -0700 Subject: [PATCH] Logout Request Reads EntityId Closes gh-12843 Closes gh-12845 --- .../ROOT/pages/servlet/saml2/logout.adoc | 10 +- .../OpenSaml4LogoutRequestResolver.java | 10 + .../OpenSaml4LogoutResponseResolver.java | 12 +- .../logout/OpenSamlLogoutRequestResolver.java | 6 +- ...outRequestValidatorParametersResolver.java | 228 ++++++++++++++++++ .../OpenSamlLogoutResponseResolver.java | 19 +- .../logout/Saml2LogoutRequestFilter.java | 143 +++++++---- ...outRequestValidatorParametersResolver.java | 45 ++++ .../logout/Saml2LogoutResponseFilter.java | 22 +- .../authentication/TestOpenSamlObjects.java | 14 ++ .../TestSaml2Authentications.java | 40 +++ ...questValidatorParametersResolverTests.java | 143 +++++++++++ .../OpenSamlLogoutResponseResolverTests.java | 2 +- 13 files changed, 639 insertions(+), 55 deletions(-) create mode 100644 saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolver.java create mode 100644 saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestValidatorParametersResolver.java create mode 100644 saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2Authentications.java create mode 100644 saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolverTests.java diff --git a/docs/modules/ROOT/pages/servlet/saml2/logout.adoc b/docs/modules/ROOT/pages/servlet/saml2/logout.adoc index 9dba271b78..aeb8d71c7c 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/logout.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/logout.adoc @@ -130,9 +130,9 @@ To add other values, you can use delegation, like so: [source,java] ---- @Bean -Saml2LogoutRequestResolver logoutRequestResolver(RelyingPartyRegistrationResolver registrationResolver) { - OpenSaml4LogoutRequestResolver logoutRequestResolver - new OpenSaml4LogoutRequestResolver(registrationResolver); +Saml2LogoutRequestResolver logoutRequestResolver(RelyingPartyRegistrationRepository registrations) { + OpenSaml4LogoutRequestResolver logoutRequestResolver = + new OpenSaml4LogoutRequestResolver(registrations); logoutRequestResolver.setParametersConsumer((parameters) -> { String name = ((Saml2AuthenticatedPrincipal) parameters.getAuthentication().getPrincipal()).getFirstAttribute("CustomAttribute"); String format = "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"; @@ -173,9 +173,9 @@ To add other values, you can use delegation, like so: [source,java] ---- @Bean -public Saml2LogoutResponseResolver logoutResponseResolver(RelyingPartyRegistrationResolver registrationResolver) { +public Saml2LogoutResponseResolver logoutResponseResolver(RelyingPartyRegistrationRepository registrations) { OpenSaml4LogoutResponseResolver logoutRequestResolver = - new OpenSaml3LogoutResponseResolver(relyingPartyRegistrationResolver); + new OpenSaml4LogoutResponseResolver(registrations); logoutRequestResolver.setParametersConsumer((parameters) -> { if (checkOtherPrevailingConditions(parameters.getRequest())) { parameters.getLogoutRequest().getStatus().getStatusCode().setCode(StatusCode.PARTIAL_LOGOUT); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java index 2c90c7891d..1252bdf703 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolver.java @@ -27,6 +27,7 @@ import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.util.Assert; @@ -47,6 +48,15 @@ public final class OpenSaml4LogoutRequestResolver implements Saml2LogoutRequestR private Clock clock = Clock.systemUTC(); + public OpenSaml4LogoutRequestResolver(RelyingPartyRegistrationRepository registrations) { + this((request, id) -> { + if (id == null) { + return null; + } + return registrations.findByRegistrationId(id); + }); + } + /** * Construct a {@link OpenSaml4LogoutRequestResolver} */ diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java index 9677bb760c..63f7c9e62b 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolver.java @@ -26,6 +26,7 @@ import org.opensaml.saml.saml2.core.LogoutResponse; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.util.Assert; @@ -45,11 +46,20 @@ public final class OpenSaml4LogoutResponseResolver implements Saml2LogoutRespons private Clock clock = Clock.systemUTC(); + public OpenSaml4LogoutResponseResolver(RelyingPartyRegistrationRepository registrations) { + this.logoutResponseResolver = new OpenSamlLogoutResponseResolver(registrations, (request, id) -> { + if (id == null) { + return null; + } + return registrations.findByRegistrationId(id); + }); + } + /** * Construct a {@link OpenSaml4LogoutResponseResolver} */ public OpenSaml4LogoutResponseResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { - this.logoutResponseResolver = new OpenSamlLogoutResponseResolver(relyingPartyRegistrationResolver); + this.logoutResponseResolver = new OpenSamlLogoutResponseResolver(null, relyingPartyRegistrationResolver); } /** diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java index 6a5c774447..6288a0434d 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java @@ -47,6 +47,8 @@ import org.springframework.security.saml2.provider.service.authentication.Saml2A import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSamlSigningUtils.QueryParametersPartial; import org.springframework.util.Assert; @@ -127,10 +129,12 @@ final class OpenSamlLogoutRequestResolver { if (registration.getAssertingPartyDetails().getSingleLogoutServiceLocation() == null) { return null; } + UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); + String entityId = uriResolver.resolve(registration.getEntityId()); LogoutRequest logoutRequest = this.logoutRequestBuilder.buildObject(); logoutRequest.setDestination(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()); Issuer issuer = this.issuerBuilder.buildObject(); - issuer.setValue(registration.getEntityId()); + issuer.setValue(entityId); logoutRequest.setIssuer(issuer); NameID nameId = this.nameIdBuilder.buildObject(); nameId.setValue(authentication.getName()); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolver.java new file mode 100644 index 0000000000..c8a10cb74f --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolver.java @@ -0,0 +1,228 @@ +/* + * Copyright 2002-2023 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.web.authentication.logout; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; + +import jakarta.servlet.http.HttpServletRequest; +import net.shibboleth.utilities.java.support.xml.ParserPool; +import org.opensaml.core.config.ConfigurationService; +import org.opensaml.core.xml.config.XMLObjectProviderRegistry; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.saml.saml2.core.LogoutRequest; +import org.opensaml.saml.saml2.core.impl.LogoutRequestUnmarshaller; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import org.springframework.http.HttpMethod; +import org.springframework.security.core.Authentication; +import org.springframework.security.saml2.Saml2Exception; +import org.springframework.security.saml2.core.OpenSamlInitializationService; +import org.springframework.security.saml2.core.Saml2Error; +import org.springframework.security.saml2.core.Saml2ErrorCodes; +import org.springframework.security.saml2.core.Saml2ParameterNames; +import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; +import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; +import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlLogoutRequestValidator; +import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; +import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; +import org.springframework.security.web.util.matcher.AntPathRequestMatcher; +import org.springframework.security.web.util.matcher.OrRequestMatcher; +import org.springframework.security.web.util.matcher.RequestMatcher; +import org.springframework.util.Assert; + +/** + * An OpenSAML-based implementation of + * {@link Saml2LogoutRequestValidatorParametersResolver} + */ +public final class OpenSamlLogoutRequestValidatorParametersResolver + implements Saml2LogoutRequestValidatorParametersResolver { + + static { + OpenSamlInitializationService.initialize(); + } + + private RequestMatcher requestMatcher = new OrRequestMatcher( + new AntPathRequestMatcher("/logout/saml2/slo/{registrationId}"), + new AntPathRequestMatcher("/logout/saml2/slo")); + + private final RelyingPartyRegistrationRepository registrations; + + private final ParserPool parserPool; + + private final LogoutRequestUnmarshaller unmarshaller; + + /** + * Constructs a {@link OpenSamlLogoutRequestValidator} + */ + public OpenSamlLogoutRequestValidatorParametersResolver(RelyingPartyRegistrationRepository registrations) { + Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); + XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); + this.parserPool = registry.getParserPool(); + this.unmarshaller = (LogoutRequestUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() + .getUnmarshaller(LogoutRequest.DEFAULT_ELEMENT_NAME); + this.registrations = registrations; + } + + /** + * Construct the parameters necessary for validating an asserting party's + * {@code } based on the given {@link HttpServletRequest} + * + *

+ * Uses the configured {@link RequestMatcher} to identify the processing request, + * including looking for any indicated {@code registrationId}. + * + *

+ * If a {@code registrationId} is found in the request, it will attempt to use that, + * erroring if no {@link RelyingPartyRegistration} is found. + * + *

+ * If no {@code registrationId} is found in the request, it will look for a currently + * logged-in user and use the associated {@code registrationId}. + * + *

+ * In the event that neither the URL nor any logged in user could determine a + * {@code registrationId}, this code then will try and derive a + * {@link RelyingPartyRegistration} given the {@code }'s + * {@code Issuer} value. + * @param request the HTTP request + * @return a {@link Saml2LogoutRequestValidatorParameters} instance, or {@code null} + * if one could not be resolved + * @throws Saml2AuthenticationException if the {@link RequestMatcher} specifies a + * non-existent {@code registrationId} + */ + @Override + public Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication) { + if (request.getParameter(Saml2ParameterNames.SAML_REQUEST) == null) { + return null; + } + RequestMatcher.MatchResult result = this.requestMatcher.matcher(request); + if (!result.isMatch()) { + return null; + } + String registrationId = getRegistrationId(result, authentication); + if (registrationId == null) { + return logoutRequestByEntityId(request, authentication); + } + return logoutRequestById(request, authentication, registrationId); + } + + /** + * The request matcher to use to identify a request to process a + * {@code }. By default, checks for {@code /logout/saml2/slo} and + * {@code /logout/saml2/slo/{registrationId}}. + * + *

+ * Generally speaking, the URL does not need to have a {@code registrationId} in it + * since either it can be looked up from the active logged in user or it can be + * derived through the {@code Issuer} in the {@code }. + * @param requestMatcher the {@link RequestMatcher} to use + */ + public void setRequestMatcher(RequestMatcher requestMatcher) { + Assert.notNull(requestMatcher, "requestMatcher cannot be null"); + this.requestMatcher = requestMatcher; + } + + private String getRegistrationId(RequestMatcher.MatchResult result, Authentication authentication) { + String registrationId = result.getVariables().get("registrationId"); + if (registrationId != null) { + return registrationId; + } + if (authentication == null) { + return null; + } + if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal principal) { + return principal.getRelyingPartyRegistrationId(); + } + return null; + } + + private Saml2LogoutRequestValidatorParameters logoutRequestById(HttpServletRequest request, + Authentication authentication, String registrationId) { + RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId); + if (registration == null) { + throw new Saml2AuthenticationException( + new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "registration not found"), + "registration not found"); + } + return logoutRequestByRegistration(request, registration, authentication); + } + + private Saml2LogoutRequestValidatorParameters logoutRequestByEntityId(HttpServletRequest request, + Authentication authentication) { + String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); + byte[] b = Saml2Utils.samlDecode(serialized); + LogoutRequest logoutRequest = parse(inflateIfRequired(request, b)); + String issuer = logoutRequest.getIssuer().getValue(); + RelyingPartyRegistration registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer); + return logoutRequestByRegistration(request, registration, authentication); + } + + private Saml2LogoutRequestValidatorParameters logoutRequestByRegistration(HttpServletRequest request, + RelyingPartyRegistration registration, Authentication authentication) { + if (registration == null) { + return null; + } + Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); + registration = fromRequest(request, registration); + String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); + Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) + .samlRequest(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)) + .binding(saml2MessageBinding).location(registration.getSingleLogoutServiceLocation()) + .parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, + request.getParameter(Saml2ParameterNames.SIG_ALG))) + .parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, + request.getParameter(Saml2ParameterNames.SIGNATURE))) + .parametersQuery((params) -> request.getQueryString()).build(); + return new Saml2LogoutRequestValidatorParameters(logoutRequest, registration, authentication); + } + + private String inflateIfRequired(HttpServletRequest request, byte[] b) { + if (HttpMethod.GET.equals(request.getMethod())) { + return Saml2Utils.samlInflate(b); + } + return new String(b, StandardCharsets.UTF_8); + } + + private LogoutRequest parse(String request) throws Saml2Exception { + try { + Document document = this.parserPool + .parse(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))); + Element element = document.getDocumentElement(); + return (LogoutRequest) this.unmarshaller.unmarshall(element); + } + catch (Exception ex) { + throw new Saml2Exception("Failed to deserialize LogoutRequest", ex); + } + } + + private RelyingPartyRegistration fromRequest(HttpServletRequest request, RelyingPartyRegistration registration) { + RelyingPartyRegistrationPlaceholderResolvers.UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers + .uriResolver(request, registration); + String entityId = uriResolver.resolve(registration.getEntityId()); + String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); + String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); + return registration.mutate().entityId(entityId).singleLogoutServiceLocation(logoutLocation) + .singleLogoutServiceResponseLocation(logoutResponseLocation).build(); + } + +} diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java index 11cc276e29..afea702c83 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java @@ -51,7 +51,10 @@ import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSamlSigningUtils.QueryParametersPartial; import org.springframework.util.Assert; @@ -82,12 +85,16 @@ final class OpenSamlLogoutResponseResolver { private final StatusCodeBuilder statusCodeBuilder; + private final RelyingPartyRegistrationRepository registrations; + private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; /** * Construct a {@link OpenSamlLogoutResponseResolver} */ - OpenSamlLogoutResponseResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { + OpenSamlLogoutResponseResolver(RelyingPartyRegistrationRepository registrations, + RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { + this.registrations = registrations; this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = registry.getParserPool(); @@ -126,19 +133,25 @@ final class OpenSamlLogoutResponseResolver { Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication, BiConsumer logoutResponseConsumer) { + LogoutRequest logoutRequest = parse(extractSamlRequest(request)); String registrationId = getRegistrationId(authentication); RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, registrationId); + if (registration == null && this.registrations != null) { + String issuer = logoutRequest.getIssuer().getValue(); + registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer); + } if (registration == null) { return null; } if (registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation() == null) { return null; } - LogoutRequest logoutRequest = parse(extractSamlRequest(request)); + UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); + String entityId = uriResolver.resolve(registration.getEntityId()); LogoutResponse logoutResponse = this.logoutResponseBuilder.buildObject(); logoutResponse.setDestination(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()); Issuer issuer = this.issuerBuilder.buildObject(); - issuer.setValue(registration.getEntityId()); + issuer.setValue(entityId); logoutResponse.setIssuer(issuer); StatusCode code = this.statusCodeBuilder.buildObject(); code.setValue(StatusCode.SUCCESS); diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java index 3ff7b00a8c..e0da44316c 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilter.java @@ -30,8 +30,11 @@ import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; +import org.springframework.security.saml2.core.Saml2Error; +import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; +import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidator; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; @@ -39,6 +42,8 @@ import org.springframework.security.saml2.provider.service.authentication.logout import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; @@ -67,9 +72,9 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder .getContextHolderStrategy(); - private final Saml2LogoutRequestValidator logoutRequestValidator; + private final Saml2LogoutRequestValidatorParametersResolver logoutRequestResolver; - private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; + private final Saml2LogoutRequestValidator logoutRequestValidator; private final Saml2LogoutResponseResolver logoutResponseResolver; @@ -77,7 +82,14 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); - private RequestMatcher logoutRequestMatcher = new AntPathRequestMatcher("/logout/saml2/slo"); + public Saml2LogoutRequestFilter(Saml2LogoutRequestValidatorParametersResolver logoutRequestResolver, + Saml2LogoutRequestValidator logoutRequestValidator, Saml2LogoutResponseResolver logoutResponseResolver, + LogoutHandler... handlers) { + this.logoutRequestResolver = logoutRequestResolver; + this.logoutRequestValidator = logoutRequestValidator; + this.logoutResponseResolver = logoutResponseResolver; + this.handler = new CompositeLogoutHandler(handlers); + } /** * Constructs a {@link Saml2LogoutResponseFilter} for accepting SAML 2.0 Logout @@ -91,7 +103,7 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { public Saml2LogoutRequestFilter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver, Saml2LogoutRequestValidator logoutRequestValidator, Saml2LogoutResponseResolver logoutResponseResolver, LogoutHandler... handlers) { - this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; + this.logoutRequestResolver = new Saml2AssertingPartyLogoutRequestResolver(relyingPartyRegistrationResolver); this.logoutRequestValidator = logoutRequestValidator; this.logoutResponseResolver = logoutResponseResolver; this.handler = new CompositeLogoutHandler(handlers); @@ -100,26 +112,21 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - - if (!this.logoutRequestMatcher.matches(request)) { - chain.doFilter(request, response); - return; - } - - if (request.getParameter(Saml2ParameterNames.SAML_REQUEST) == null) { - chain.doFilter(request, response); - return; - } - Authentication authentication = this.securityContextHolderStrategy.getContext().getAuthentication(); - RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, - getRegistrationId(authentication)); - if (registration == null) { - this.logger - .trace("Did not process logout request since failed to find associated RelyingPartyRegistration"); + Saml2LogoutRequestValidatorParameters parameters; + try { + parameters = this.logoutRequestResolver.resolve(request, authentication); + } + catch (Saml2AuthenticationException ex) { + this.logger.trace("Did not process logout request since failed to find requested RelyingPartyRegistration"); response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } + if (parameters == null) { + chain.doFilter(request, response); + return; + } + RelyingPartyRegistration registration = parameters.getRelyingPartyRegistration(); if (registration.getSingleLogoutServiceLocation() == null) { this.logger.trace( "Did not process logout request since RelyingPartyRegistration has not been configured with a logout request endpoint"); @@ -134,17 +141,6 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { return; } - String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); - Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) - .samlRequest(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)) - .binding(saml2MessageBinding).location(registration.getSingleLogoutServiceLocation()) - .parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, - request.getParameter(Saml2ParameterNames.SIG_ALG))) - .parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, - request.getParameter(Saml2ParameterNames.SIGNATURE))) - .parametersQuery((params) -> request.getQueryString()).build(); - Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(logoutRequest, - registration, authentication); Saml2LogoutValidatorResult result = this.logoutRequestValidator.validate(parameters); if (result.hasErrors()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, result.getErrors().iterator().next().toString()); @@ -168,7 +164,10 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); - this.logoutRequestMatcher = logoutRequestMatcher; + Assert.isInstanceOf(Saml2AssertingPartyLogoutRequestResolver.class, this.logoutRequestResolver, + "saml2LogoutRequestResolver and logoutRequestMatcher cannot both be set. Please set the request matcher in the saml2LogoutRequestResolver itself."); + ((Saml2AssertingPartyLogoutRequestResolver) this.logoutRequestResolver) + .setLogoutRequestMatcher(logoutRequestMatcher); } /** @@ -182,17 +181,6 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { this.securityContextHolderStrategy = securityContextHolderStrategy; } - private String getRegistrationId(Authentication authentication) { - if (authentication == null) { - return null; - } - Object principal = authentication.getPrincipal(); - if (principal instanceof Saml2AuthenticatedPrincipal) { - return ((Saml2AuthenticatedPrincipal) principal).getRelyingPartyRegistrationId(); - } - return null; - } - private void doRedirect(HttpServletRequest request, HttpServletResponse response, Saml2LogoutResponse logoutResponse) throws IOException { String location = logoutResponse.getResponseLocation(); @@ -252,4 +240,73 @@ public final class Saml2LogoutRequestFilter extends OncePerRequestFilter { return html.toString(); } + private static class Saml2AssertingPartyLogoutRequestResolver + implements Saml2LogoutRequestValidatorParametersResolver { + + private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; + + private RequestMatcher logoutRequestMatcher = new AntPathRequestMatcher("/logout/saml2/slo"); + + Saml2AssertingPartyLogoutRequestResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { + this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; + } + + @Override + public Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, + Authentication authentication) { + String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); + if (serialized == null) { + return null; + } + RequestMatcher.MatchResult result = this.logoutRequestMatcher.matcher(request); + if (!result.isMatch()) { + return null; + } + String registrationId = getRegistrationId(result, authentication); + RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, + registrationId); + if (registration == null) { + throw new Saml2AuthenticationException( + new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "registration not found"), + "registration not found"); + } + UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); + String entityId = uriResolver.resolve(registration.getEntityId()); + String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); + String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); + registration = registration.mutate().entityId(entityId).singleLogoutServiceLocation(logoutLocation) + .singleLogoutServiceResponseLocation(logoutResponseLocation).build(); + Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); + Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) + .samlRequest(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)) + .binding(saml2MessageBinding).location(registration.getSingleLogoutServiceLocation()) + .parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, + request.getParameter(Saml2ParameterNames.SIG_ALG))) + .parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, + request.getParameter(Saml2ParameterNames.SIGNATURE))) + .parametersQuery((params) -> request.getQueryString()).build(); + return new Saml2LogoutRequestValidatorParameters(logoutRequest, registration, authentication); + } + + void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { + Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); + this.logoutRequestMatcher = logoutRequestMatcher; + } + + private String getRegistrationId(RequestMatcher.MatchResult result, Authentication authentication) { + String registrationId = result.getVariables().get("registrationId"); + if (registrationId != null) { + return registrationId; + } + if (authentication == null) { + return null; + } + if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal principal) { + return principal.getRelyingPartyRegistrationId(); + } + return null; + } + + } + } diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestValidatorParametersResolver.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestValidatorParametersResolver.java new file mode 100644 index 0000000000..46adcea02a --- /dev/null +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestValidatorParametersResolver.java @@ -0,0 +1,45 @@ +/* + * Copyright 2002-2023 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.web.authentication.logout; + +import jakarta.servlet.http.HttpServletRequest; + +import org.springframework.security.core.Authentication; +import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; + +/** + * Resolved a SAML 2.0 Logout Request and associated validation parameters from the given + * {@link HttpServletRequest} and current {@link Authentication}. + * + * The returned logout request is suitable for validating, logging out the logged-in user, + * and initiating the construction of a {@code LogoutResponse}. + * + * @author Josh Cummings + * @since 6.1 + */ +public interface Saml2LogoutRequestValidatorParametersResolver { + + /** + * Resolve any SAML 2.0 Logout Request and associated + * {@link org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration} + * @param request the HTTP request + * @param authentication the current user, if any; may be null + * @return a SAML 2.0 Logout Request, if any; may be null + */ + Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication); + +} diff --git a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java index 346a4ec7a2..ae6f684f9a 100644 --- a/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java +++ b/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java @@ -35,7 +35,10 @@ import org.springframework.security.saml2.provider.service.authentication.logout import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidatorParameters; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; +import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; @@ -71,6 +74,18 @@ public final class Saml2LogoutResponseFilter extends OncePerRequestFilter { private RequestMatcher logoutRequestMatcher = new AntPathRequestMatcher("/logout/saml2/slo"); + public Saml2LogoutResponseFilter(RelyingPartyRegistrationRepository registrations, + Saml2LogoutResponseValidator logoutResponseValidator, LogoutSuccessHandler logoutSuccessHandler) { + this.relyingPartyRegistrationResolver = (request, id) -> { + if (id == null) { + return null; + } + return registrations.findByRegistrationId(id); + }; + this.logoutResponseValidator = logoutResponseValidator; + this.logoutSuccessHandler = logoutSuccessHandler; + } + /** * Constructs a {@link Saml2LogoutResponseFilter} for accepting SAML 2.0 Logout * Responses from the asserting party @@ -125,7 +140,12 @@ public final class Saml2LogoutResponseFilter extends OncePerRequestFilter { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } - + UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); + String entityId = uriResolver.resolve(registration.getEntityId()); + String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); + String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); + registration = registration.mutate().entityId(entityId).singleLogoutServiceLocation(logoutLocation) + .singleLogoutServiceResponseLocation(logoutResponseLocation).build(); Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); if (!registration.getSingleLogoutServiceBindings().contains(saml2MessageBinding)) { this.logger.trace("Did not process logout response since used incorrect binding"); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java index 1727d3e4bc..5fd9b3076d 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java @@ -101,6 +101,8 @@ public final class TestOpenSamlObjects { private static String DESTINATION = "https://localhost/login/saml2/sso/idp-alias"; + private static String LOGOUT_DESTINATION = "http://localhost/logout/saml2/slo"; + public static String RELYING_PARTY_ENTITY_ID = "https://localhost/saml2/service-provider-metadata/idp-alias"; private static String ASSERTING_PARTY_ENTITY_ID = "https://some.idp.test/saml2/idp"; @@ -204,6 +206,18 @@ public final class TestOpenSamlObjects { return authnRequest; } + public static LogoutRequest logoutRequest() { + Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); + issuer.setValue(ASSERTING_PARTY_ENTITY_ID); + NameID nameId = build(NameID.DEFAULT_ELEMENT_NAME); + nameId.setValue("user"); + LogoutRequest logoutRequest = build(LogoutRequest.DEFAULT_ELEMENT_NAME); + logoutRequest.setIssuer(issuer); + logoutRequest.setDestination(LOGOUT_DESTINATION); + logoutRequest.setNameID(nameId); + return logoutRequest; + } + static Credential getSigningCredential(Saml2X509Credential credential, String entityId) { BasicCredential cred = getBasicCredential(credential); cred.setEntityId(entityId); diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2Authentications.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2Authentications.java new file mode 100644 index 0000000000..8cfbfc0a29 --- /dev/null +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2Authentications.java @@ -0,0 +1,40 @@ +/* + * Copyright 2002-2023 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.authentication; + +import java.util.Collections; + +import org.springframework.security.core.authority.AuthorityUtils; + +/** + * Tests instances for {@link Saml2Authentication} + * + * @author Josh Cummings + */ +public final class TestSaml2Authentications { + + private TestSaml2Authentications() { + } + + public static Saml2Authentication authentication() { + DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", + Collections.emptyMap()); + principal.setRelyingPartyRegistrationId("simplesamlphp"); + return new Saml2Authentication(principal, "response", AuthorityUtils.createAuthorityList("ROLE_USER")); + } + +} diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolverTests.java new file mode 100644 index 0000000000..719f079cb3 --- /dev/null +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolverTests.java @@ -0,0 +1,143 @@ +/* + * Copyright 2002-2023 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.security.saml2.provider.service.web.authentication.logout; + +import java.nio.charset.StandardCharsets; + +import net.shibboleth.utilities.java.support.xml.SerializeSupport; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.opensaml.core.xml.XMLObject; +import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; +import org.opensaml.core.xml.io.Marshaller; +import org.opensaml.core.xml.io.MarshallingException; +import org.w3c.dom.Element; + +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.security.authentication.TestingAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.saml2.Saml2Exception; +import org.springframework.security.saml2.core.Saml2ParameterNames; +import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; +import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; +import org.springframework.security.saml2.provider.service.authentication.TestSaml2Authentications; +import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; +import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; +import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.BDDMockito.given; + +@ExtendWith(MockitoExtension.class) +public final class OpenSamlLogoutRequestValidatorParametersResolverTests { + + @Mock + RelyingPartyRegistrationRepository registrations; + + private RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); + + private OpenSamlLogoutRequestValidatorParametersResolver resolver; + + @BeforeEach + void setup() { + this.resolver = new OpenSamlLogoutRequestValidatorParametersResolver(this.registrations); + } + + @Test + void saml2LogoutRegistrationIdResolveWhenMatchesThenParameters() { + String registrationId = this.registration.getRegistrationId(); + MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId); + Authentication authentication = new TestingAuthenticationToken("user", "pass"); + request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); + given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration); + Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication); + assertThat(parameters.getAuthentication()).isEqualTo(authentication); + assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); + assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request"); + } + + @Test + void saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters() { + String registrationId = this.registration.getRegistrationId(); + MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId); + request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); + given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration); + Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null); + assertThat(parameters.getAuthentication()).isNull(); + assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); + assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request"); + } + + @Test + void saml2LogoutResolveWhenAuthenticatedThenParameters() { + String registrationId = this.registration.getRegistrationId(); + MockHttpServletRequest request = post("/logout/saml2/slo"); + Authentication authentication = TestSaml2Authentications.authentication(); + request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); + given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration); + Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication); + assertThat(parameters.getAuthentication()).isEqualTo(authentication); + assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); + assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request"); + } + + @Test + void saml2LogoutResolveWhenUnauthenticatedThenParameters() { + String registrationId = this.registration.getRegistrationId(); + MockHttpServletRequest request = post("/logout/saml2/slo"); + String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest()); + String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8)); + request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded); + given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)) + .willReturn(this.registration); + Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null); + assertThat(parameters.getAuthentication()).isNull(); + assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); + assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded); + } + + @Test + void saml2LogoutRegistrationIdResolveWhenNoMatchingRegistrationIdThenSaml2Exception() { + MockHttpServletRequest request = post("/logout/saml2/slo/id"); + request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); + assertThatExceptionOfType(Saml2AuthenticationException.class) + .isThrownBy(() -> this.resolver.resolve(request, null)); + } + + private MockHttpServletRequest post(String uri) { + MockHttpServletRequest request = new MockHttpServletRequest("POST", uri); + request.setServletPath(uri); + return request; + } + + private String serialize(XMLObject object) { + try { + Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); + Element element = marshaller.marshall(object); + return SerializeSupport.nodeToString(element); + } + catch (MarshallingException ex) { + throw new Saml2Exception(ex); + } + } + +} diff --git a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolverTests.java b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolverTests.java index f2407e85df..aed45c0b3d 100644 --- a/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolverTests.java +++ b/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolverTests.java @@ -56,7 +56,7 @@ public class OpenSamlLogoutResponseResolverTests { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); - OpenSamlLogoutResponseResolver logoutResponseResolver = new OpenSamlLogoutResponseResolver( + OpenSamlLogoutResponseResolver logoutResponseResolver = new OpenSamlLogoutResponseResolver(null, this.relyingPartyRegistrationResolver); @Test