21 changed files with 1613 additions and 804 deletions
109
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java → saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/BaseOpenSamlLogoutRequestResolver.java
109
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java → saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/BaseOpenSamlLogoutRequestResolver.java
@ -0,0 +1,199 @@ |
|||||||
|
/* |
||||||
|
* Copyright 2002-2024 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.opensaml.saml.saml2.core.LogoutRequest; |
||||||
|
|
||||||
|
import org.springframework.http.HttpMethod; |
||||||
|
import org.springframework.security.core.Authentication; |
||||||
|
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.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} |
||||||
|
*/ |
||||||
|
final class BaseOpenSamlLogoutRequestValidatorParametersResolver |
||||||
|
implements Saml2LogoutRequestValidatorParametersResolver { |
||||||
|
|
||||||
|
static { |
||||||
|
OpenSamlInitializationService.initialize(); |
||||||
|
} |
||||||
|
|
||||||
|
private final OpenSamlOperations saml; |
||||||
|
|
||||||
|
private final RelyingPartyRegistrationRepository registrations; |
||||||
|
|
||||||
|
private RequestMatcher requestMatcher = new OrRequestMatcher( |
||||||
|
new AntPathRequestMatcher("/logout/saml2/slo/{registrationId}"), |
||||||
|
new AntPathRequestMatcher("/logout/saml2/slo")); |
||||||
|
|
||||||
|
/** |
||||||
|
* Constructs a {@link BaseOpenSamlLogoutRequestValidatorParametersResolver} |
||||||
|
*/ |
||||||
|
BaseOpenSamlLogoutRequestValidatorParametersResolver(OpenSamlOperations saml, |
||||||
|
RelyingPartyRegistrationRepository registrations) { |
||||||
|
Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); |
||||||
|
this.saml = saml; |
||||||
|
this.registrations = registrations; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Construct the parameters necessary for validating an asserting party's |
||||||
|
* {@code <saml2:LogoutRequest>} based on the given {@link HttpServletRequest} |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* Uses the configured {@link RequestMatcher} to identify the processing request, |
||||||
|
* including looking for any indicated {@code registrationId}. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* If a {@code registrationId} is found in the request, it will attempt to use that, |
||||||
|
* erroring if no {@link RelyingPartyRegistration} is found. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* If no {@code registrationId} is found in the request, it will look for a currently |
||||||
|
* logged-in user and use the associated {@code registrationId}. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* 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 <saml2:LogoutRequest>}'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 <saml2:LogoutRequest>}. By default, checks for {@code /logout/saml2/slo} and |
||||||
|
* {@code /logout/saml2/slo/{registrationId}}. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* 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 <saml2:LogoutRequest>}. |
||||||
|
* @param requestMatcher the {@link RequestMatcher} to use |
||||||
|
*/ |
||||||
|
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); |
||||||
|
LogoutRequest logoutRequest = this.saml.deserialize( |
||||||
|
Saml2Utils.withEncoded(serialized).inflate(HttpMethod.GET.matches(request.getMethod())).decode()); |
||||||
|
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 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(); |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
150
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java → saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/BaseOpenSamlLogoutResponseResolver.java
150
saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java → saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/BaseOpenSamlLogoutResponseResolver.java
@ -0,0 +1,100 @@ |
|||||||
|
/* |
||||||
|
* 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.core.OpenSamlInitializationService; |
||||||
|
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; |
||||||
|
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.web.util.matcher.RequestMatcher; |
||||||
|
import org.springframework.util.Assert; |
||||||
|
|
||||||
|
/** |
||||||
|
* An OpenSAML-based implementation of |
||||||
|
* {@link Saml2LogoutRequestValidatorParametersResolver} |
||||||
|
*/ |
||||||
|
public final class OpenSaml4LogoutRequestValidatorParametersResolver |
||||||
|
implements Saml2LogoutRequestValidatorParametersResolver { |
||||||
|
|
||||||
|
static { |
||||||
|
OpenSamlInitializationService.initialize(); |
||||||
|
} |
||||||
|
|
||||||
|
private final BaseOpenSamlLogoutRequestValidatorParametersResolver delegate; |
||||||
|
|
||||||
|
/** |
||||||
|
* Constructs a {@link OpenSaml4LogoutRequestValidatorParametersResolver} |
||||||
|
*/ |
||||||
|
public OpenSaml4LogoutRequestValidatorParametersResolver(RelyingPartyRegistrationRepository registrations) { |
||||||
|
Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); |
||||||
|
this.delegate = new BaseOpenSamlLogoutRequestValidatorParametersResolver(new OpenSaml4Template(), |
||||||
|
registrations); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* Construct the parameters necessary for validating an asserting party's |
||||||
|
* {@code <saml2:LogoutRequest>} based on the given {@link HttpServletRequest} |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* Uses the configured {@link RequestMatcher} to identify the processing request, |
||||||
|
* including looking for any indicated {@code registrationId}. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* If a {@code registrationId} is found in the request, it will attempt to use that, |
||||||
|
* erroring if no {@link RelyingPartyRegistration} is found. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* If no {@code registrationId} is found in the request, it will look for a currently |
||||||
|
* logged-in user and use the associated {@code registrationId}. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* 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 <saml2:LogoutRequest>}'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) { |
||||||
|
return this.delegate.resolve(request, authentication); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* The request matcher to use to identify a request to process a |
||||||
|
* {@code <saml2:LogoutRequest>}. By default, checks for {@code /logout/saml2/slo} and |
||||||
|
* {@code /logout/saml2/slo/{registrationId}}. |
||||||
|
* |
||||||
|
* <p> |
||||||
|
* 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 <saml2:LogoutRequest>}. |
||||||
|
* @param requestMatcher the {@link RequestMatcher} to use |
||||||
|
*/ |
||||||
|
public void setRequestMatcher(RequestMatcher requestMatcher) { |
||||||
|
Assert.notNull(requestMatcher, "requestMatcher cannot be null"); |
||||||
|
this.delegate.setRequestMatcher(requestMatcher); |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
@ -0,0 +1,617 @@ |
|||||||
|
/* |
||||||
|
* Copyright 2002-2024 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.io.InputStream; |
||||||
|
import java.nio.charset.StandardCharsets; |
||||||
|
import java.security.PrivateKey; |
||||||
|
import java.security.cert.X509Certificate; |
||||||
|
import java.util.ArrayList; |
||||||
|
import java.util.Arrays; |
||||||
|
import java.util.Collection; |
||||||
|
import java.util.Collections; |
||||||
|
import java.util.HashSet; |
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Map; |
||||||
|
import java.util.Set; |
||||||
|
|
||||||
|
import javax.xml.namespace.QName; |
||||||
|
|
||||||
|
import net.shibboleth.utilities.java.support.resolver.CriteriaSet; |
||||||
|
import net.shibboleth.utilities.java.support.xml.SerializeSupport; |
||||||
|
import org.apache.commons.logging.Log; |
||||||
|
import org.apache.commons.logging.LogFactory; |
||||||
|
import org.opensaml.core.criterion.EntityIdCriterion; |
||||||
|
import org.opensaml.core.xml.XMLObject; |
||||||
|
import org.opensaml.core.xml.XMLObjectBuilder; |
||||||
|
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; |
||||||
|
import org.opensaml.core.xml.io.Marshaller; |
||||||
|
import org.opensaml.core.xml.io.MarshallingException; |
||||||
|
import org.opensaml.core.xml.io.Unmarshaller; |
||||||
|
import org.opensaml.core.xml.io.UnmarshallerFactory; |
||||||
|
import org.opensaml.core.xml.util.XMLObjectSupport; |
||||||
|
import org.opensaml.saml.common.xml.SAMLConstants; |
||||||
|
import org.opensaml.saml.criterion.ProtocolCriterion; |
||||||
|
import org.opensaml.saml.ext.saml2delrestrict.Delegate; |
||||||
|
import org.opensaml.saml.ext.saml2delrestrict.DelegationRestrictionType; |
||||||
|
import org.opensaml.saml.metadata.criteria.role.impl.EvaluableProtocolRoleDescriptorCriterion; |
||||||
|
import org.opensaml.saml.saml2.core.Assertion; |
||||||
|
import org.opensaml.saml.saml2.core.Attribute; |
||||||
|
import org.opensaml.saml.saml2.core.AttributeStatement; |
||||||
|
import org.opensaml.saml.saml2.core.Condition; |
||||||
|
import org.opensaml.saml.saml2.core.EncryptedAssertion; |
||||||
|
import org.opensaml.saml.saml2.core.EncryptedAttribute; |
||||||
|
import org.opensaml.saml.saml2.core.Issuer; |
||||||
|
import org.opensaml.saml.saml2.core.LogoutRequest; |
||||||
|
import org.opensaml.saml.saml2.core.NameID; |
||||||
|
import org.opensaml.saml.saml2.core.RequestAbstractType; |
||||||
|
import org.opensaml.saml.saml2.core.Response; |
||||||
|
import org.opensaml.saml.saml2.core.StatusResponseType; |
||||||
|
import org.opensaml.saml.saml2.core.Subject; |
||||||
|
import org.opensaml.saml.saml2.core.SubjectConfirmation; |
||||||
|
import org.opensaml.saml.saml2.encryption.Decrypter; |
||||||
|
import org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; |
||||||
|
import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; |
||||||
|
import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; |
||||||
|
import org.opensaml.security.SecurityException; |
||||||
|
import org.opensaml.security.credential.BasicCredential; |
||||||
|
import org.opensaml.security.credential.Credential; |
||||||
|
import org.opensaml.security.credential.CredentialResolver; |
||||||
|
import org.opensaml.security.credential.CredentialSupport; |
||||||
|
import org.opensaml.security.credential.UsageType; |
||||||
|
import org.opensaml.security.credential.criteria.impl.EvaluableEntityIDCredentialCriterion; |
||||||
|
import org.opensaml.security.credential.criteria.impl.EvaluableUsageCredentialCriterion; |
||||||
|
import org.opensaml.security.credential.impl.CollectionCredentialResolver; |
||||||
|
import org.opensaml.security.criteria.UsageCriterion; |
||||||
|
import org.opensaml.security.x509.BasicX509Credential; |
||||||
|
import org.opensaml.xmlsec.SignatureSigningParameters; |
||||||
|
import org.opensaml.xmlsec.SignatureSigningParametersResolver; |
||||||
|
import org.opensaml.xmlsec.config.impl.DefaultSecurityConfigurationBootstrap; |
||||||
|
import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; |
||||||
|
import org.opensaml.xmlsec.crypto.XMLSigningUtil; |
||||||
|
import org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver; |
||||||
|
import org.opensaml.xmlsec.encryption.support.DecryptionException; |
||||||
|
import org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver; |
||||||
|
import org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver; |
||||||
|
import org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver; |
||||||
|
import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; |
||||||
|
import org.opensaml.xmlsec.keyinfo.KeyInfoCredentialResolver; |
||||||
|
import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; |
||||||
|
import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; |
||||||
|
import org.opensaml.xmlsec.keyinfo.impl.CollectionKeyInfoCredentialResolver; |
||||||
|
import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; |
||||||
|
import org.opensaml.xmlsec.signature.SignableXMLObject; |
||||||
|
import org.opensaml.xmlsec.signature.Signature; |
||||||
|
import org.opensaml.xmlsec.signature.support.SignatureConstants; |
||||||
|
import org.opensaml.xmlsec.signature.support.SignatureSupport; |
||||||
|
import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; |
||||||
|
import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine; |
||||||
|
import org.w3c.dom.Document; |
||||||
|
import org.w3c.dom.Element; |
||||||
|
|
||||||
|
import org.springframework.security.saml2.Saml2Exception; |
||||||
|
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.core.Saml2X509Credential; |
||||||
|
import org.springframework.util.Assert; |
||||||
|
import org.springframework.web.util.UriComponentsBuilder; |
||||||
|
import org.springframework.web.util.UriUtils; |
||||||
|
|
||||||
|
/** |
||||||
|
* For internal use only. Subject to breaking changes at any time. |
||||||
|
*/ |
||||||
|
final class OpenSaml4Template implements OpenSamlOperations { |
||||||
|
|
||||||
|
private static final Log logger = LogFactory.getLog(OpenSaml4Template.class); |
||||||
|
|
||||||
|
@Override |
||||||
|
public <T extends XMLObject> T build(QName elementName) { |
||||||
|
XMLObjectBuilder<?> builder = XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(elementName); |
||||||
|
if (builder == null) { |
||||||
|
throw new Saml2Exception("Unable to resolve Builder for " + elementName); |
||||||
|
} |
||||||
|
return (T) builder.buildObject(elementName); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public <T extends XMLObject> T deserialize(String serialized) { |
||||||
|
return deserialize(new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8))); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public <T extends XMLObject> T deserialize(InputStream serialized) { |
||||||
|
try { |
||||||
|
Document document = XMLObjectProviderRegistrySupport.getParserPool().parse(serialized); |
||||||
|
Element element = document.getDocumentElement(); |
||||||
|
UnmarshallerFactory factory = XMLObjectProviderRegistrySupport.getUnmarshallerFactory(); |
||||||
|
Unmarshaller unmarshaller = factory.getUnmarshaller(element); |
||||||
|
if (unmarshaller == null) { |
||||||
|
throw new Saml2Exception("Unsupported element of type " + element.getTagName()); |
||||||
|
} |
||||||
|
return (T) unmarshaller.unmarshall(element); |
||||||
|
} |
||||||
|
catch (Saml2Exception ex) { |
||||||
|
throw ex; |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
throw new Saml2Exception("Failed to deserialize payload", ex); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4SerializationConfigurer serialize(XMLObject object) { |
||||||
|
Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); |
||||||
|
try { |
||||||
|
return serialize(marshaller.marshall(object)); |
||||||
|
} |
||||||
|
catch (MarshallingException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4SerializationConfigurer serialize(Element element) { |
||||||
|
return new OpenSaml4SerializationConfigurer(element); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4SignatureConfigurer withSigningKeys(Collection<Saml2X509Credential> credentials) { |
||||||
|
return new OpenSaml4SignatureConfigurer(credentials); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4VerificationConfigurer withVerificationKeys(Collection<Saml2X509Credential> credentials) { |
||||||
|
return new OpenSaml4VerificationConfigurer(credentials); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4DecryptionConfigurer withDecryptionKeys(Collection<Saml2X509Credential> credentials) { |
||||||
|
return new OpenSaml4DecryptionConfigurer(credentials); |
||||||
|
} |
||||||
|
|
||||||
|
OpenSaml4Template() { |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
static final class OpenSaml4SerializationConfigurer |
||||||
|
implements SerializationConfigurer<OpenSaml4SerializationConfigurer> { |
||||||
|
|
||||||
|
private final Element element; |
||||||
|
|
||||||
|
boolean pretty; |
||||||
|
|
||||||
|
OpenSaml4SerializationConfigurer(Element element) { |
||||||
|
this.element = element; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4SerializationConfigurer prettyPrint(boolean pretty) { |
||||||
|
this.pretty = pretty; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String serialize() { |
||||||
|
if (this.pretty) { |
||||||
|
return SerializeSupport.prettyPrintXML(this.element); |
||||||
|
} |
||||||
|
return SerializeSupport.nodeToString(this.element); |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
static final class OpenSaml4SignatureConfigurer implements SignatureConfigurer<OpenSaml4SignatureConfigurer> { |
||||||
|
|
||||||
|
private final Collection<Saml2X509Credential> credentials; |
||||||
|
|
||||||
|
private final Map<String, String> components = new LinkedHashMap<>(); |
||||||
|
|
||||||
|
private List<String> algs = List.of(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); |
||||||
|
|
||||||
|
OpenSaml4SignatureConfigurer(Collection<Saml2X509Credential> credentials) { |
||||||
|
this.credentials = credentials; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public OpenSaml4SignatureConfigurer algorithms(List<String> algs) { |
||||||
|
this.algs = algs; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public <O extends SignableXMLObject> O sign(O object) { |
||||||
|
SignatureSigningParameters parameters = resolveSigningParameters(); |
||||||
|
try { |
||||||
|
SignatureSupport.signObject(object, parameters); |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
return object; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public Map<String, String> sign(Map<String, String> params) { |
||||||
|
SignatureSigningParameters parameters = resolveSigningParameters(); |
||||||
|
this.components.putAll(params); |
||||||
|
Credential credential = parameters.getSigningCredential(); |
||||||
|
String algorithmUri = parameters.getSignatureAlgorithm(); |
||||||
|
this.components.put(Saml2ParameterNames.SIG_ALG, algorithmUri); |
||||||
|
UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); |
||||||
|
for (Map.Entry<String, String> component : this.components.entrySet()) { |
||||||
|
builder.queryParam(component.getKey(), |
||||||
|
UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); |
||||||
|
} |
||||||
|
String queryString = builder.build(true).toString().substring(1); |
||||||
|
try { |
||||||
|
byte[] rawSignature = XMLSigningUtil.signWithURI(credential, algorithmUri, |
||||||
|
queryString.getBytes(StandardCharsets.UTF_8)); |
||||||
|
String b64Signature = Saml2Utils.samlEncode(rawSignature); |
||||||
|
this.components.put(Saml2ParameterNames.SIGNATURE, b64Signature); |
||||||
|
} |
||||||
|
catch (SecurityException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
return this.components; |
||||||
|
} |
||||||
|
|
||||||
|
private SignatureSigningParameters resolveSigningParameters() { |
||||||
|
List<Credential> credentials = resolveSigningCredentials(); |
||||||
|
List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); |
||||||
|
String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; |
||||||
|
SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); |
||||||
|
BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); |
||||||
|
signingConfiguration.setSigningCredentials(credentials); |
||||||
|
signingConfiguration.setSignatureAlgorithms(this.algs); |
||||||
|
signingConfiguration.setSignatureReferenceDigestMethods(digests); |
||||||
|
signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); |
||||||
|
signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); |
||||||
|
CriteriaSet criteria = new CriteriaSet(new SignatureSigningConfigurationCriterion(signingConfiguration)); |
||||||
|
try { |
||||||
|
SignatureSigningParameters parameters = resolver.resolveSingle(criteria); |
||||||
|
Assert.notNull(parameters, "Failed to resolve any signing credential"); |
||||||
|
return parameters; |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { |
||||||
|
final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); |
||||||
|
|
||||||
|
namedManager.setUseDefaultManager(true); |
||||||
|
final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); |
||||||
|
|
||||||
|
// Generator for X509Credentials
|
||||||
|
final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); |
||||||
|
x509Factory.setEmitEntityCertificate(true); |
||||||
|
x509Factory.setEmitEntityCertificateChain(true); |
||||||
|
|
||||||
|
defaultManager.registerFactory(x509Factory); |
||||||
|
|
||||||
|
return namedManager; |
||||||
|
} |
||||||
|
|
||||||
|
private List<Credential> resolveSigningCredentials() { |
||||||
|
List<Credential> credentials = new ArrayList<>(); |
||||||
|
for (Saml2X509Credential x509Credential : this.credentials) { |
||||||
|
X509Certificate certificate = x509Credential.getCertificate(); |
||||||
|
PrivateKey privateKey = x509Credential.getPrivateKey(); |
||||||
|
BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); |
||||||
|
credential.setUsageType(UsageType.SIGNING); |
||||||
|
credentials.add(credential); |
||||||
|
} |
||||||
|
return credentials; |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
static final class OpenSaml4VerificationConfigurer implements VerificationConfigurer { |
||||||
|
|
||||||
|
private final Collection<Saml2X509Credential> credentials; |
||||||
|
|
||||||
|
private String entityId; |
||||||
|
|
||||||
|
OpenSaml4VerificationConfigurer(Collection<Saml2X509Credential> credentials) { |
||||||
|
this.credentials = credentials; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public VerificationConfigurer entityId(String entityId) { |
||||||
|
this.entityId = entityId; |
||||||
|
return this; |
||||||
|
} |
||||||
|
|
||||||
|
private SignatureTrustEngine trustEngine(Collection<Saml2X509Credential> keys) { |
||||||
|
Set<Credential> credentials = new HashSet<>(); |
||||||
|
for (Saml2X509Credential key : keys) { |
||||||
|
BasicX509Credential cred = new BasicX509Credential(key.getCertificate()); |
||||||
|
cred.setUsageType(UsageType.SIGNING); |
||||||
|
cred.setEntityId(this.entityId); |
||||||
|
credentials.add(cred); |
||||||
|
} |
||||||
|
CredentialResolver credentialsResolver = new CollectionCredentialResolver(credentials); |
||||||
|
return new ExplicitKeySignatureTrustEngine(credentialsResolver, |
||||||
|
DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver()); |
||||||
|
} |
||||||
|
|
||||||
|
private CriteriaSet verificationCriteria(Issuer issuer) { |
||||||
|
return new CriteriaSet(new EvaluableEntityIDCredentialCriterion(new EntityIdCriterion(issuer.getValue())), |
||||||
|
new EvaluableProtocolRoleDescriptorCriterion(new ProtocolCriterion(SAMLConstants.SAML20P_NS)), |
||||||
|
new EvaluableUsageCredentialCriterion(new UsageCriterion(UsageType.SIGNING))); |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public Collection<Saml2Error> verify(SignableXMLObject signable) { |
||||||
|
if (signable instanceof StatusResponseType response) { |
||||||
|
return verifySignature(response.getID(), response.getIssuer(), response.getSignature()); |
||||||
|
} |
||||||
|
if (signable instanceof RequestAbstractType request) { |
||||||
|
return verifySignature(request.getID(), request.getIssuer(), request.getSignature()); |
||||||
|
} |
||||||
|
if (signable instanceof Assertion assertion) { |
||||||
|
return verifySignature(assertion.getID(), assertion.getIssuer(), assertion.getSignature()); |
||||||
|
} |
||||||
|
throw new Saml2Exception("Unsupported object of type: " + signable.getClass().getName()); |
||||||
|
} |
||||||
|
|
||||||
|
private Collection<Saml2Error> verifySignature(String id, Issuer issuer, Signature signature) { |
||||||
|
SignatureTrustEngine trustEngine = trustEngine(this.credentials); |
||||||
|
CriteriaSet criteria = verificationCriteria(issuer); |
||||||
|
Collection<Saml2Error> errors = new ArrayList<>(); |
||||||
|
SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); |
||||||
|
try { |
||||||
|
profileValidator.validate(signature); |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Invalid signature for object [" + id + "]: ")); |
||||||
|
} |
||||||
|
|
||||||
|
try { |
||||||
|
if (!trustEngine.validate(signature, criteria)) { |
||||||
|
errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Invalid signature for object [" + id + "]")); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Invalid signature for object [" + id + "]: ")); |
||||||
|
} |
||||||
|
|
||||||
|
return errors; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public Collection<Saml2Error> verify(RedirectParameters parameters) { |
||||||
|
SignatureTrustEngine trustEngine = trustEngine(this.credentials); |
||||||
|
CriteriaSet criteria = verificationCriteria(parameters.getIssuer()); |
||||||
|
if (parameters.getAlgorithm() == null) { |
||||||
|
return Collections.singletonList(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Missing signature algorithm for object [" + parameters.getId() + "]")); |
||||||
|
} |
||||||
|
if (!parameters.hasSignature()) { |
||||||
|
return Collections.singletonList(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Missing signature for object [" + parameters.getId() + "]")); |
||||||
|
} |
||||||
|
Collection<Saml2Error> errors = new ArrayList<>(); |
||||||
|
String algorithmUri = parameters.getAlgorithm(); |
||||||
|
try { |
||||||
|
if (!trustEngine.validate(parameters.getSignature(), parameters.getContent(), algorithmUri, criteria, |
||||||
|
null)) { |
||||||
|
errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Invalid signature for object [" + parameters.getId() + "]")); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, |
||||||
|
"Invalid signature for object [" + parameters.getId() + "]: ")); |
||||||
|
} |
||||||
|
return errors; |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
static final class OpenSaml4DecryptionConfigurer implements DecryptionConfigurer { |
||||||
|
|
||||||
|
private static final EncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver( |
||||||
|
Arrays.asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(), |
||||||
|
new SimpleRetrievalMethodEncryptedKeyResolver())); |
||||||
|
|
||||||
|
private final Decrypter decrypter; |
||||||
|
|
||||||
|
OpenSaml4DecryptionConfigurer(Collection<Saml2X509Credential> decryptionCredentials) { |
||||||
|
this.decrypter = decrypter(decryptionCredentials); |
||||||
|
} |
||||||
|
|
||||||
|
private static Decrypter decrypter(Collection<Saml2X509Credential> decryptionCredentials) { |
||||||
|
Collection<Credential> credentials = new ArrayList<>(); |
||||||
|
for (Saml2X509Credential key : decryptionCredentials) { |
||||||
|
Credential cred = CredentialSupport.getSimpleCredential(key.getCertificate(), key.getPrivateKey()); |
||||||
|
credentials.add(cred); |
||||||
|
} |
||||||
|
KeyInfoCredentialResolver resolver = new CollectionKeyInfoCredentialResolver(credentials); |
||||||
|
Decrypter decrypter = new Decrypter(null, resolver, encryptedKeyResolver); |
||||||
|
decrypter.setRootInNewDocument(true); |
||||||
|
return decrypter; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public void decrypt(XMLObject object) { |
||||||
|
if (object instanceof Response response) { |
||||||
|
decryptResponse(response); |
||||||
|
return; |
||||||
|
} |
||||||
|
if (object instanceof Assertion assertion) { |
||||||
|
decryptAssertion(assertion); |
||||||
|
} |
||||||
|
if (object instanceof LogoutRequest request) { |
||||||
|
decryptLogoutRequest(request); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
/* |
||||||
|
* The methods that follow are adapted from OpenSAML's {@link DecryptAssertions}, |
||||||
|
* {@link DecryptNameIDs}, and {@link DecryptAttributes}. |
||||||
|
* |
||||||
|
* <p>The reason that these OpenSAML classes are not used directly is because they |
||||||
|
* reference {@link javax.servlet.http.HttpServletRequest} which is a lower |
||||||
|
* Servlet API version than what Spring Security SAML uses. |
||||||
|
* |
||||||
|
* If OpenSAML 5 updates to {@link jakarta.servlet.http.HttpServletRequest}, then |
||||||
|
* this arrangement can be revisited. |
||||||
|
*/ |
||||||
|
|
||||||
|
private void decryptResponse(Response response) { |
||||||
|
Collection<Assertion> decrypteds = new ArrayList<>(); |
||||||
|
Collection<EncryptedAssertion> encrypteds = new ArrayList<>(); |
||||||
|
|
||||||
|
int count = 0; |
||||||
|
int size = response.getEncryptedAssertions().size(); |
||||||
|
for (EncryptedAssertion encrypted : response.getEncryptedAssertions()) { |
||||||
|
logger.trace(String.format("Decrypting EncryptedAssertion (%d/%d) in Response [%s]", count, size, |
||||||
|
response.getID())); |
||||||
|
try { |
||||||
|
Assertion decrypted = this.decrypter.decrypt(encrypted); |
||||||
|
if (decrypted != null) { |
||||||
|
encrypteds.add(encrypted); |
||||||
|
decrypteds.add(decrypted); |
||||||
|
} |
||||||
|
count++; |
||||||
|
} |
||||||
|
catch (DecryptionException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
response.getEncryptedAssertions().removeAll(encrypteds); |
||||||
|
response.getAssertions().addAll(decrypteds); |
||||||
|
|
||||||
|
// Re-marshall the response so that any ID attributes within the decrypted
|
||||||
|
// Assertions
|
||||||
|
// will have their ID-ness re-established at the DOM level.
|
||||||
|
if (!decrypteds.isEmpty()) { |
||||||
|
try { |
||||||
|
XMLObjectSupport.marshall(response); |
||||||
|
} |
||||||
|
catch (final MarshallingException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private void decryptAssertion(Assertion assertion) { |
||||||
|
for (AttributeStatement statement : assertion.getAttributeStatements()) { |
||||||
|
decryptAttributes(statement); |
||||||
|
} |
||||||
|
decryptSubject(assertion.getSubject()); |
||||||
|
if (assertion.getConditions() != null) { |
||||||
|
for (Condition c : assertion.getConditions().getConditions()) { |
||||||
|
if (!(c instanceof DelegationRestrictionType delegation)) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
for (Delegate d : delegation.getDelegates()) { |
||||||
|
if (d.getEncryptedID() != null) { |
||||||
|
try { |
||||||
|
NameID decrypted = (NameID) this.decrypter.decrypt(d.getEncryptedID()); |
||||||
|
if (decrypted != null) { |
||||||
|
d.setNameID(decrypted); |
||||||
|
d.setEncryptedID(null); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (DecryptionException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private void decryptAttributes(AttributeStatement statement) { |
||||||
|
Collection<Attribute> decrypteds = new ArrayList<>(); |
||||||
|
Collection<EncryptedAttribute> encrypteds = new ArrayList<>(); |
||||||
|
for (EncryptedAttribute encrypted : statement.getEncryptedAttributes()) { |
||||||
|
try { |
||||||
|
Attribute decrypted = this.decrypter.decrypt(encrypted); |
||||||
|
if (decrypted != null) { |
||||||
|
encrypteds.add(encrypted); |
||||||
|
decrypteds.add(decrypted); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (Exception ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
statement.getEncryptedAttributes().removeAll(encrypteds); |
||||||
|
statement.getAttributes().addAll(decrypteds); |
||||||
|
} |
||||||
|
|
||||||
|
private void decryptSubject(Subject subject) { |
||||||
|
if (subject != null) { |
||||||
|
if (subject.getEncryptedID() != null) { |
||||||
|
try { |
||||||
|
NameID decrypted = (NameID) this.decrypter.decrypt(subject.getEncryptedID()); |
||||||
|
if (decrypted != null) { |
||||||
|
subject.setNameID(decrypted); |
||||||
|
subject.setEncryptedID(null); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (final DecryptionException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
for (final SubjectConfirmation sc : subject.getSubjectConfirmations()) { |
||||||
|
if (sc.getEncryptedID() != null) { |
||||||
|
try { |
||||||
|
NameID decrypted = (NameID) this.decrypter.decrypt(sc.getEncryptedID()); |
||||||
|
if (decrypted != null) { |
||||||
|
sc.setNameID(decrypted); |
||||||
|
sc.setEncryptedID(null); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (final DecryptionException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private void decryptLogoutRequest(LogoutRequest request) { |
||||||
|
if (request.getEncryptedID() != null) { |
||||||
|
try { |
||||||
|
NameID decrypted = (NameID) this.decrypter.decrypt(request.getEncryptedID()); |
||||||
|
if (decrypted != null) { |
||||||
|
request.setNameID(decrypted); |
||||||
|
request.setEncryptedID(null); |
||||||
|
} |
||||||
|
} |
||||||
|
catch (DecryptionException ex) { |
||||||
|
throw new Saml2Exception(ex); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
@ -0,0 +1,184 @@ |
|||||||
|
/* |
||||||
|
* Copyright 2002-2024 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.InputStream; |
||||||
|
import java.nio.charset.StandardCharsets; |
||||||
|
import java.util.Collection; |
||||||
|
import java.util.List; |
||||||
|
import java.util.Map; |
||||||
|
import java.util.Objects; |
||||||
|
|
||||||
|
import javax.xml.namespace.QName; |
||||||
|
|
||||||
|
import org.opensaml.core.xml.XMLObject; |
||||||
|
import org.opensaml.saml.saml2.core.Issuer; |
||||||
|
import org.opensaml.saml.saml2.core.RequestAbstractType; |
||||||
|
import org.opensaml.saml.saml2.core.StatusResponseType; |
||||||
|
import org.opensaml.xmlsec.signature.SignableXMLObject; |
||||||
|
import org.w3c.dom.Element; |
||||||
|
|
||||||
|
import org.springframework.security.saml2.core.Saml2Error; |
||||||
|
import org.springframework.security.saml2.core.Saml2ParameterNames; |
||||||
|
import org.springframework.security.saml2.core.Saml2X509Credential; |
||||||
|
import org.springframework.web.util.UriComponentsBuilder; |
||||||
|
|
||||||
|
interface OpenSamlOperations { |
||||||
|
|
||||||
|
<T extends XMLObject> T build(QName elementName); |
||||||
|
|
||||||
|
<T extends XMLObject> T deserialize(String serialized); |
||||||
|
|
||||||
|
<T extends XMLObject> T deserialize(InputStream serialized); |
||||||
|
|
||||||
|
SerializationConfigurer<?> serialize(XMLObject object); |
||||||
|
|
||||||
|
SerializationConfigurer<?> serialize(Element element); |
||||||
|
|
||||||
|
SignatureConfigurer<?> withSigningKeys(Collection<Saml2X509Credential> credentials); |
||||||
|
|
||||||
|
VerificationConfigurer withVerificationKeys(Collection<Saml2X509Credential> credentials); |
||||||
|
|
||||||
|
DecryptionConfigurer withDecryptionKeys(Collection<Saml2X509Credential> credentials); |
||||||
|
|
||||||
|
interface SerializationConfigurer<B extends SerializationConfigurer<B>> { |
||||||
|
|
||||||
|
B prettyPrint(boolean pretty); |
||||||
|
|
||||||
|
String serialize(); |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
interface SignatureConfigurer<B extends SignatureConfigurer<B>> { |
||||||
|
|
||||||
|
B algorithms(List<String> algs); |
||||||
|
|
||||||
|
<O extends SignableXMLObject> O sign(O object); |
||||||
|
|
||||||
|
Map<String, String> sign(Map<String, String> params); |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
interface VerificationConfigurer { |
||||||
|
|
||||||
|
VerificationConfigurer entityId(String entityId); |
||||||
|
|
||||||
|
Collection<Saml2Error> verify(SignableXMLObject signable); |
||||||
|
|
||||||
|
Collection<Saml2Error> verify(VerificationConfigurer.RedirectParameters parameters); |
||||||
|
|
||||||
|
final class RedirectParameters { |
||||||
|
|
||||||
|
private final String id; |
||||||
|
|
||||||
|
private final Issuer issuer; |
||||||
|
|
||||||
|
private final String algorithm; |
||||||
|
|
||||||
|
private final byte[] signature; |
||||||
|
|
||||||
|
private final byte[] content; |
||||||
|
|
||||||
|
RedirectParameters(Map<String, String> parameters, String parametersQuery, RequestAbstractType request) { |
||||||
|
this.id = request.getID(); |
||||||
|
this.issuer = request.getIssuer(); |
||||||
|
this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); |
||||||
|
if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { |
||||||
|
this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); |
||||||
|
} |
||||||
|
else { |
||||||
|
this.signature = null; |
||||||
|
} |
||||||
|
Map<String, String> queryParams = UriComponentsBuilder.newInstance() |
||||||
|
.query(parametersQuery) |
||||||
|
.build(true) |
||||||
|
.getQueryParams() |
||||||
|
.toSingleValueMap(); |
||||||
|
String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); |
||||||
|
this.content = getContent(Saml2ParameterNames.SAML_REQUEST, relayState, queryParams); |
||||||
|
} |
||||||
|
|
||||||
|
RedirectParameters(Map<String, String> parameters, String parametersQuery, StatusResponseType response) { |
||||||
|
this.id = response.getID(); |
||||||
|
this.issuer = response.getIssuer(); |
||||||
|
this.algorithm = parameters.get(Saml2ParameterNames.SIG_ALG); |
||||||
|
if (parameters.get(Saml2ParameterNames.SIGNATURE) != null) { |
||||||
|
this.signature = Saml2Utils.samlDecode(parameters.get(Saml2ParameterNames.SIGNATURE)); |
||||||
|
} |
||||||
|
else { |
||||||
|
this.signature = null; |
||||||
|
} |
||||||
|
Map<String, String> queryParams = UriComponentsBuilder.newInstance() |
||||||
|
.query(parametersQuery) |
||||||
|
.build(true) |
||||||
|
.getQueryParams() |
||||||
|
.toSingleValueMap(); |
||||||
|
String relayState = parameters.get(Saml2ParameterNames.RELAY_STATE); |
||||||
|
this.content = getContent(Saml2ParameterNames.SAML_RESPONSE, relayState, queryParams); |
||||||
|
} |
||||||
|
|
||||||
|
static byte[] getContent(String samlObject, String relayState, final Map<String, String> queryParams) { |
||||||
|
if (Objects.nonNull(relayState)) { |
||||||
|
return String |
||||||
|
.format("%s=%s&%s=%s&%s=%s", samlObject, queryParams.get(samlObject), |
||||||
|
Saml2ParameterNames.RELAY_STATE, queryParams.get(Saml2ParameterNames.RELAY_STATE), |
||||||
|
Saml2ParameterNames.SIG_ALG, queryParams.get(Saml2ParameterNames.SIG_ALG)) |
||||||
|
.getBytes(StandardCharsets.UTF_8); |
||||||
|
} |
||||||
|
else { |
||||||
|
return String |
||||||
|
.format("%s=%s&%s=%s", samlObject, queryParams.get(samlObject), Saml2ParameterNames.SIG_ALG, |
||||||
|
queryParams.get(Saml2ParameterNames.SIG_ALG)) |
||||||
|
.getBytes(StandardCharsets.UTF_8); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
String getId() { |
||||||
|
return this.id; |
||||||
|
} |
||||||
|
|
||||||
|
Issuer getIssuer() { |
||||||
|
return this.issuer; |
||||||
|
} |
||||||
|
|
||||||
|
byte[] getContent() { |
||||||
|
return this.content; |
||||||
|
} |
||||||
|
|
||||||
|
String getAlgorithm() { |
||||||
|
return this.algorithm; |
||||||
|
} |
||||||
|
|
||||||
|
byte[] getSignature() { |
||||||
|
return this.signature; |
||||||
|
} |
||||||
|
|
||||||
|
boolean hasSignature() { |
||||||
|
return this.signature != null; |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
interface DecryptionConfigurer { |
||||||
|
|
||||||
|
void decrypt(XMLObject object); |
||||||
|
|
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
@ -1,194 +0,0 @@ |
|||||||
/* |
|
||||||
* Copyright 2002-2021 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 java.security.PrivateKey; |
|
||||||
import java.security.cert.X509Certificate; |
|
||||||
import java.util.ArrayList; |
|
||||||
import java.util.Collections; |
|
||||||
import java.util.LinkedHashMap; |
|
||||||
import java.util.List; |
|
||||||
import java.util.Map; |
|
||||||
|
|
||||||
import net.shibboleth.utilities.java.support.resolver.CriteriaSet; |
|
||||||
import net.shibboleth.utilities.java.support.xml.SerializeSupport; |
|
||||||
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.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; |
|
||||||
import org.opensaml.security.SecurityException; |
|
||||||
import org.opensaml.security.credential.BasicCredential; |
|
||||||
import org.opensaml.security.credential.Credential; |
|
||||||
import org.opensaml.security.credential.CredentialSupport; |
|
||||||
import org.opensaml.security.credential.UsageType; |
|
||||||
import org.opensaml.xmlsec.SignatureSigningParameters; |
|
||||||
import org.opensaml.xmlsec.SignatureSigningParametersResolver; |
|
||||||
import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; |
|
||||||
import org.opensaml.xmlsec.crypto.XMLSigningUtil; |
|
||||||
import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; |
|
||||||
import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; |
|
||||||
import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; |
|
||||||
import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; |
|
||||||
import org.opensaml.xmlsec.signature.SignableXMLObject; |
|
||||||
import org.opensaml.xmlsec.signature.support.SignatureConstants; |
|
||||||
import org.opensaml.xmlsec.signature.support.SignatureSupport; |
|
||||||
import org.w3c.dom.Element; |
|
||||||
|
|
||||||
import org.springframework.security.saml2.Saml2Exception; |
|
||||||
import org.springframework.security.saml2.core.Saml2ParameterNames; |
|
||||||
import org.springframework.security.saml2.core.Saml2X509Credential; |
|
||||||
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; |
|
||||||
import org.springframework.util.Assert; |
|
||||||
import org.springframework.web.util.UriComponentsBuilder; |
|
||||||
import org.springframework.web.util.UriUtils; |
|
||||||
|
|
||||||
/** |
|
||||||
* Utility methods for signing SAML components with OpenSAML |
|
||||||
* |
|
||||||
* For internal use only. |
|
||||||
* |
|
||||||
* @author Josh Cummings |
|
||||||
*/ |
|
||||||
final class OpenSamlSigningUtils { |
|
||||||
|
|
||||||
static 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); |
|
||||||
} |
|
||||||
} |
|
||||||
|
|
||||||
static <O extends SignableXMLObject> O sign(O object, RelyingPartyRegistration relyingPartyRegistration) { |
|
||||||
SignatureSigningParameters parameters = resolveSigningParameters(relyingPartyRegistration); |
|
||||||
try { |
|
||||||
SignatureSupport.signObject(object, parameters); |
|
||||||
return object; |
|
||||||
} |
|
||||||
catch (Exception ex) { |
|
||||||
throw new Saml2Exception(ex); |
|
||||||
} |
|
||||||
} |
|
||||||
|
|
||||||
static QueryParametersPartial sign(RelyingPartyRegistration registration) { |
|
||||||
return new QueryParametersPartial(registration); |
|
||||||
} |
|
||||||
|
|
||||||
private static SignatureSigningParameters resolveSigningParameters( |
|
||||||
RelyingPartyRegistration relyingPartyRegistration) { |
|
||||||
List<Credential> credentials = resolveSigningCredentials(relyingPartyRegistration); |
|
||||||
List<String> algorithms = relyingPartyRegistration.getAssertingPartyMetadata().getSigningAlgorithms(); |
|
||||||
List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); |
|
||||||
String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; |
|
||||||
SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); |
|
||||||
CriteriaSet criteria = new CriteriaSet(); |
|
||||||
BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); |
|
||||||
signingConfiguration.setSigningCredentials(credentials); |
|
||||||
signingConfiguration.setSignatureAlgorithms(algorithms); |
|
||||||
signingConfiguration.setSignatureReferenceDigestMethods(digests); |
|
||||||
signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); |
|
||||||
signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); |
|
||||||
criteria.add(new SignatureSigningConfigurationCriterion(signingConfiguration)); |
|
||||||
try { |
|
||||||
SignatureSigningParameters parameters = resolver.resolveSingle(criteria); |
|
||||||
Assert.notNull(parameters, "Failed to resolve any signing credential"); |
|
||||||
return parameters; |
|
||||||
} |
|
||||||
catch (Exception ex) { |
|
||||||
throw new Saml2Exception(ex); |
|
||||||
} |
|
||||||
} |
|
||||||
|
|
||||||
private static NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { |
|
||||||
final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); |
|
||||||
|
|
||||||
namedManager.setUseDefaultManager(true); |
|
||||||
final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); |
|
||||||
|
|
||||||
// Generator for X509Credentials
|
|
||||||
final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); |
|
||||||
x509Factory.setEmitEntityCertificate(true); |
|
||||||
x509Factory.setEmitEntityCertificateChain(true); |
|
||||||
|
|
||||||
defaultManager.registerFactory(x509Factory); |
|
||||||
|
|
||||||
return namedManager; |
|
||||||
} |
|
||||||
|
|
||||||
private static List<Credential> resolveSigningCredentials(RelyingPartyRegistration relyingPartyRegistration) { |
|
||||||
List<Credential> credentials = new ArrayList<>(); |
|
||||||
for (Saml2X509Credential x509Credential : relyingPartyRegistration.getSigningX509Credentials()) { |
|
||||||
X509Certificate certificate = x509Credential.getCertificate(); |
|
||||||
PrivateKey privateKey = x509Credential.getPrivateKey(); |
|
||||||
BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); |
|
||||||
credential.setEntityId(relyingPartyRegistration.getEntityId()); |
|
||||||
credential.setUsageType(UsageType.SIGNING); |
|
||||||
credentials.add(credential); |
|
||||||
} |
|
||||||
return credentials; |
|
||||||
} |
|
||||||
|
|
||||||
private OpenSamlSigningUtils() { |
|
||||||
|
|
||||||
} |
|
||||||
|
|
||||||
static class QueryParametersPartial { |
|
||||||
|
|
||||||
final RelyingPartyRegistration registration; |
|
||||||
|
|
||||||
final Map<String, String> components = new LinkedHashMap<>(); |
|
||||||
|
|
||||||
QueryParametersPartial(RelyingPartyRegistration registration) { |
|
||||||
this.registration = registration; |
|
||||||
} |
|
||||||
|
|
||||||
QueryParametersPartial param(String key, String value) { |
|
||||||
this.components.put(key, value); |
|
||||||
return this; |
|
||||||
} |
|
||||||
|
|
||||||
Map<String, String> parameters() { |
|
||||||
SignatureSigningParameters parameters = resolveSigningParameters(this.registration); |
|
||||||
Credential credential = parameters.getSigningCredential(); |
|
||||||
String algorithmUri = parameters.getSignatureAlgorithm(); |
|
||||||
this.components.put(Saml2ParameterNames.SIG_ALG, algorithmUri); |
|
||||||
UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); |
|
||||||
for (Map.Entry<String, String> component : this.components.entrySet()) { |
|
||||||
builder.queryParam(component.getKey(), |
|
||||||
UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); |
|
||||||
} |
|
||||||
String queryString = builder.build(true).toString().substring(1); |
|
||||||
try { |
|
||||||
byte[] rawSignature = XMLSigningUtil.signWithURI(credential, algorithmUri, |
|
||||||
queryString.getBytes(StandardCharsets.UTF_8)); |
|
||||||
String b64Signature = Saml2Utils.samlEncode(rawSignature); |
|
||||||
this.components.put(Saml2ParameterNames.SIGNATURE, b64Signature); |
|
||||||
} |
|
||||||
catch (SecurityException ex) { |
|
||||||
throw new Saml2Exception(ex); |
|
||||||
} |
|
||||||
return this.components; |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
@ -0,0 +1,153 @@ |
|||||||
|
/* |
||||||
|
* 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 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.springframework.mock.web.MockHttpServletRequest; |
||||||
|
import org.springframework.security.authentication.TestingAuthenticationToken; |
||||||
|
import org.springframework.security.core.Authentication; |
||||||
|
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 OpenSaml4LogoutRequestValidatorParametersResolverTests { |
||||||
|
|
||||||
|
@Mock |
||||||
|
RelyingPartyRegistrationRepository registrations; |
||||||
|
|
||||||
|
private final OpenSamlOperations saml = new OpenSaml4Template(); |
||||||
|
|
||||||
|
private RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); |
||||||
|
|
||||||
|
private OpenSaml4LogoutRequestValidatorParametersResolver resolver; |
||||||
|
|
||||||
|
@BeforeEach |
||||||
|
void setup() { |
||||||
|
this.resolver = new OpenSaml4LogoutRequestValidatorParametersResolver(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 saml2LogoutResolveWhenUnauthenticatedGetRequestThenInflates() { |
||||||
|
String registrationId = this.registration.getRegistrationId(); |
||||||
|
MockHttpServletRequest request = get("/logout/saml2/slo"); |
||||||
|
String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest()); |
||||||
|
String encoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(logoutRequest)); |
||||||
|
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 MockHttpServletRequest get(String uri) { |
||||||
|
MockHttpServletRequest request = new MockHttpServletRequest("GET", uri); |
||||||
|
request.setServletPath(uri); |
||||||
|
return request; |
||||||
|
} |
||||||
|
|
||||||
|
private String serialize(XMLObject object) { |
||||||
|
return this.saml.serialize(object).serialize(); |
||||||
|
} |
||||||
|
|
||||||
|
} |
||||||
@ -1,121 +0,0 @@ |
|||||||
/* |
|
||||||
* Copyright 2002-2022 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 java.util.ArrayList; |
|
||||||
import java.util.Arrays; |
|
||||||
import java.util.HashMap; |
|
||||||
|
|
||||||
import jakarta.servlet.http.HttpServletRequest; |
|
||||||
import org.junit.jupiter.api.Test; |
|
||||||
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; |
|
||||||
import org.opensaml.saml.saml2.core.LogoutRequest; |
|
||||||
import org.w3c.dom.Document; |
|
||||||
import org.w3c.dom.Element; |
|
||||||
|
|
||||||
import org.springframework.mock.web.MockHttpServletRequest; |
|
||||||
import org.springframework.security.saml2.Saml2Exception; |
|
||||||
import org.springframework.security.saml2.core.Saml2ParameterNames; |
|
||||||
import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; |
|
||||||
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; |
|
||||||
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.registration.TestRelyingPartyRegistrations; |
|
||||||
import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; |
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat; |
|
||||||
import static org.mockito.ArgumentMatchers.any; |
|
||||||
import static org.mockito.BDDMockito.given; |
|
||||||
import static org.mockito.Mockito.mock; |
|
||||||
|
|
||||||
/** |
|
||||||
* Tests for {@link OpenSamlLogoutRequestResolver} |
|
||||||
* |
|
||||||
* @author Josh Cummings |
|
||||||
*/ |
|
||||||
public class OpenSamlLogoutRequestResolverTests { |
|
||||||
|
|
||||||
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); |
|
||||||
|
|
||||||
OpenSamlLogoutRequestResolver logoutRequestResolver = new OpenSamlLogoutRequestResolver( |
|
||||||
this.relyingPartyRegistrationResolver); |
|
||||||
|
|
||||||
@Test |
|
||||||
public void resolveRedirectWhenAuthenticatedThenIncludesName() { |
|
||||||
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); |
|
||||||
Saml2Authentication authentication = authentication(registration); |
|
||||||
HttpServletRequest request = new MockHttpServletRequest(); |
|
||||||
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); |
|
||||||
Saml2LogoutRequest saml2LogoutRequest = this.logoutRequestResolver.resolve(request, authentication); |
|
||||||
assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIG_ALG)).isNotNull(); |
|
||||||
assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIGNATURE)).isNotNull(); |
|
||||||
assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.RELAY_STATE)).isNotNull(); |
|
||||||
Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); |
|
||||||
LogoutRequest logoutRequest = getLogoutRequest(saml2LogoutRequest.getSamlRequest(), binding); |
|
||||||
assertThat(logoutRequest.getNameID().getValue()).isEqualTo(authentication.getName()); |
|
||||||
} |
|
||||||
|
|
||||||
@Test |
|
||||||
public void resolvePostWhenAuthenticatedThenIncludesName() { |
|
||||||
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() |
|
||||||
.assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)) |
|
||||||
.build(); |
|
||||||
Saml2Authentication authentication = authentication(registration); |
|
||||||
HttpServletRequest request = new MockHttpServletRequest(); |
|
||||||
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); |
|
||||||
Saml2LogoutRequest saml2LogoutRequest = this.logoutRequestResolver.resolve(request, authentication); |
|
||||||
assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIG_ALG)).isNull(); |
|
||||||
assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIGNATURE)).isNull(); |
|
||||||
assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.RELAY_STATE)).isNotNull(); |
|
||||||
Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); |
|
||||||
LogoutRequest logoutRequest = getLogoutRequest(saml2LogoutRequest.getSamlRequest(), binding); |
|
||||||
assertThat(logoutRequest.getNameID().getValue()).isEqualTo(authentication.getName()); |
|
||||||
assertThat(logoutRequest.getSessionIndexes()).hasSize(1); |
|
||||||
assertThat(logoutRequest.getSessionIndexes().get(0).getValue()).isEqualTo("session-index"); |
|
||||||
} |
|
||||||
|
|
||||||
private Saml2Authentication authentication(RelyingPartyRegistration registration) { |
|
||||||
DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", new HashMap<>(), |
|
||||||
Arrays.asList("session-index")); |
|
||||||
principal.setRelyingPartyRegistrationId(registration.getRegistrationId()); |
|
||||||
return new Saml2Authentication(principal, "response", new ArrayList<>()); |
|
||||||
} |
|
||||||
|
|
||||||
private LogoutRequest getLogoutRequest(String samlRequest, Saml2MessageBinding binding) { |
|
||||||
if (binding == Saml2MessageBinding.REDIRECT) { |
|
||||||
samlRequest = Saml2Utils.samlInflate(Saml2Utils.samlDecode(samlRequest)); |
|
||||||
} |
|
||||||
else { |
|
||||||
samlRequest = new String(Saml2Utils.samlDecode(samlRequest), StandardCharsets.UTF_8); |
|
||||||
} |
|
||||||
try { |
|
||||||
Document document = XMLObjectProviderRegistrySupport.getParserPool() |
|
||||||
.parse(new ByteArrayInputStream(samlRequest.getBytes(StandardCharsets.UTF_8))); |
|
||||||
Element element = document.getDocumentElement(); |
|
||||||
return (LogoutRequest) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() |
|
||||||
.getUnmarshaller(element) |
|
||||||
.unmarshall(element); |
|
||||||
} |
|
||||||
catch (Exception ex) { |
|
||||||
throw new Saml2Exception(ex); |
|
||||||
} |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
@ -1,153 +0,0 @@ |
|||||||
/* |
|
||||||
* Copyright 2002-2021 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 java.util.ArrayList; |
|
||||||
import java.util.HashMap; |
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test; |
|
||||||
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; |
|
||||||
import org.opensaml.saml.saml2.core.LogoutRequest; |
|
||||||
import org.opensaml.saml.saml2.core.LogoutResponse; |
|
||||||
import org.opensaml.saml.saml2.core.StatusCode; |
|
||||||
import org.w3c.dom.Document; |
|
||||||
import org.w3c.dom.Element; |
|
||||||
|
|
||||||
import org.springframework.mock.web.MockHttpServletRequest; |
|
||||||
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.DefaultSaml2AuthenticatedPrincipal; |
|
||||||
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; |
|
||||||
import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; |
|
||||||
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.Saml2MessageBinding; |
|
||||||
import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; |
|
||||||
import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; |
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat; |
|
||||||
import static org.mockito.ArgumentMatchers.any; |
|
||||||
import static org.mockito.BDDMockito.given; |
|
||||||
import static org.mockito.Mockito.mock; |
|
||||||
|
|
||||||
/** |
|
||||||
* Tests for {@link OpenSamlLogoutResponseResolver} |
|
||||||
* |
|
||||||
* @author Josh Cummings |
|
||||||
*/ |
|
||||||
public class OpenSamlLogoutResponseResolverTests { |
|
||||||
|
|
||||||
RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); |
|
||||||
|
|
||||||
OpenSamlLogoutResponseResolver logoutResponseResolver = new OpenSamlLogoutResponseResolver(null, |
|
||||||
this.relyingPartyRegistrationResolver); |
|
||||||
|
|
||||||
@Test |
|
||||||
public void resolveRedirectWhenAuthenticatedThenSuccess() { |
|
||||||
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); |
|
||||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
|
||||||
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); |
|
||||||
request.setParameter(Saml2ParameterNames.SAML_REQUEST, |
|
||||||
Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())); |
|
||||||
request.setParameter(Saml2ParameterNames.RELAY_STATE, "abcd"); |
|
||||||
Authentication authentication = authentication(registration); |
|
||||||
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); |
|
||||||
Saml2LogoutResponse saml2LogoutResponse = this.logoutResponseResolver.resolve(request, authentication); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIG_ALG)).isNotNull(); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIGNATURE)).isNotNull(); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.RELAY_STATE)).isSameAs("abcd"); |
|
||||||
Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); |
|
||||||
LogoutResponse logoutResponse = getLogoutResponse(saml2LogoutResponse.getSamlResponse(), binding); |
|
||||||
assertThat(logoutResponse.getStatus().getStatusCode().getValue()).isEqualTo(StatusCode.SUCCESS); |
|
||||||
} |
|
||||||
|
|
||||||
@Test |
|
||||||
public void resolvePostWhenAuthenticatedThenSuccess() { |
|
||||||
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() |
|
||||||
.assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)) |
|
||||||
.build(); |
|
||||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
|
||||||
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); |
|
||||||
request.setParameter(Saml2ParameterNames.SAML_REQUEST, |
|
||||||
Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())); |
|
||||||
request.setParameter(Saml2ParameterNames.RELAY_STATE, "abcd"); |
|
||||||
Authentication authentication = authentication(registration); |
|
||||||
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); |
|
||||||
Saml2LogoutResponse saml2LogoutResponse = this.logoutResponseResolver.resolve(request, authentication); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIG_ALG)).isNull(); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIGNATURE)).isNull(); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.RELAY_STATE)).isSameAs("abcd"); |
|
||||||
Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); |
|
||||||
LogoutResponse logoutResponse = getLogoutResponse(saml2LogoutResponse.getSamlResponse(), binding); |
|
||||||
assertThat(logoutResponse.getStatus().getStatusCode().getValue()).isEqualTo(StatusCode.SUCCESS); |
|
||||||
} |
|
||||||
|
|
||||||
// gh-10923
|
|
||||||
@Test |
|
||||||
public void resolvePostWithLineBreaksWhenAuthenticatedThenSuccess() { |
|
||||||
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() |
|
||||||
.assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)) |
|
||||||
.build(); |
|
||||||
MockHttpServletRequest request = new MockHttpServletRequest(); |
|
||||||
LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); |
|
||||||
String encoded = new StringBuffer( |
|
||||||
Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())) |
|
||||||
.insert(10, "\r\n") |
|
||||||
.toString(); |
|
||||||
request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded); |
|
||||||
request.setParameter(Saml2ParameterNames.RELAY_STATE, "abcd"); |
|
||||||
Authentication authentication = authentication(registration); |
|
||||||
given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); |
|
||||||
Saml2LogoutResponse saml2LogoutResponse = this.logoutResponseResolver.resolve(request, authentication); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIG_ALG)).isNull(); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIGNATURE)).isNull(); |
|
||||||
assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.RELAY_STATE)).isSameAs("abcd"); |
|
||||||
Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); |
|
||||||
LogoutResponse logoutResponse = getLogoutResponse(saml2LogoutResponse.getSamlResponse(), binding); |
|
||||||
assertThat(logoutResponse.getStatus().getStatusCode().getValue()).isEqualTo(StatusCode.SUCCESS); |
|
||||||
} |
|
||||||
|
|
||||||
private Saml2Authentication authentication(RelyingPartyRegistration registration) { |
|
||||||
DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", new HashMap<>()); |
|
||||||
principal.setRelyingPartyRegistrationId(registration.getRegistrationId()); |
|
||||||
return new Saml2Authentication(principal, "response", new ArrayList<>()); |
|
||||||
} |
|
||||||
|
|
||||||
private LogoutResponse getLogoutResponse(String saml2Response, Saml2MessageBinding binding) { |
|
||||||
if (binding == Saml2MessageBinding.REDIRECT) { |
|
||||||
saml2Response = Saml2Utils.samlInflate(Saml2Utils.samlDecode(saml2Response)); |
|
||||||
} |
|
||||||
else { |
|
||||||
saml2Response = new String(Saml2Utils.samlDecode(saml2Response), StandardCharsets.UTF_8); |
|
||||||
} |
|
||||||
try { |
|
||||||
Document document = XMLObjectProviderRegistrySupport.getParserPool() |
|
||||||
.parse(new ByteArrayInputStream(saml2Response.getBytes(StandardCharsets.UTF_8))); |
|
||||||
Element element = document.getDocumentElement(); |
|
||||||
return (LogoutResponse) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() |
|
||||||
.getUnmarshaller(element) |
|
||||||
.unmarshall(element); |
|
||||||
} |
|
||||||
catch (Exception ex) { |
|
||||||
throw new Saml2Exception(ex); |
|
||||||
} |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
@ -1,91 +0,0 @@ |
|||||||
/* |
|
||||||
* Copyright 2002-2021 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.util.UUID; |
|
||||||
|
|
||||||
import javax.xml.namespace.QName; |
|
||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach; |
|
||||||
import org.junit.jupiter.api.Test; |
|
||||||
import org.opensaml.core.xml.XMLObject; |
|
||||||
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; |
|
||||||
import org.opensaml.saml.common.SAMLVersion; |
|
||||||
import org.opensaml.saml.saml2.core.Issuer; |
|
||||||
import org.opensaml.saml.saml2.core.Response; |
|
||||||
import org.opensaml.xmlsec.signature.Signature; |
|
||||||
|
|
||||||
import org.springframework.security.saml2.core.OpenSamlInitializationService; |
|
||||||
import org.springframework.security.saml2.core.TestSaml2X509Credentials; |
|
||||||
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; |
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat; |
|
||||||
|
|
||||||
/** |
|
||||||
* Test open SAML signatures |
|
||||||
*/ |
|
||||||
public class OpenSamlSigningUtilsTests { |
|
||||||
|
|
||||||
static { |
|
||||||
OpenSamlInitializationService.initialize(); |
|
||||||
} |
|
||||||
|
|
||||||
private RelyingPartyRegistration registration; |
|
||||||
|
|
||||||
@BeforeEach |
|
||||||
public void setup() { |
|
||||||
this.registration = RelyingPartyRegistration.withRegistrationId("saml-idp") |
|
||||||
.entityId("https://some.idp.example.com/entity-id") |
|
||||||
.signingX509Credentials((c) -> { |
|
||||||
c.add(TestSaml2X509Credentials.relyingPartySigningCredential()); |
|
||||||
c.add(TestSaml2X509Credentials.assertingPartySigningCredential()); |
|
||||||
}) |
|
||||||
.assertingPartyDetails((c) -> c.entityId("https://some.idp.example.com/entity-id") |
|
||||||
.singleSignOnServiceLocation("https://some.idp.example.com/service-location")) |
|
||||||
.build(); |
|
||||||
} |
|
||||||
|
|
||||||
@Test |
|
||||||
public void whenSigningAnObjectThenKeyInfoIsPartOfTheSignature() { |
|
||||||
Response response = response("destination", "issuer"); |
|
||||||
OpenSamlSigningUtils.sign(response, this.registration); |
|
||||||
Signature signature = response.getSignature(); |
|
||||||
assertThat(signature).isNotNull(); |
|
||||||
assertThat(signature.getKeyInfo()).isNotNull(); |
|
||||||
} |
|
||||||
|
|
||||||
Response response(String destination, String issuerEntityId) { |
|
||||||
Response response = build(Response.DEFAULT_ELEMENT_NAME); |
|
||||||
response.setID("R" + UUID.randomUUID()); |
|
||||||
response.setVersion(SAMLVersion.VERSION_20); |
|
||||||
response.setID("_" + UUID.randomUUID()); |
|
||||||
response.setDestination(destination); |
|
||||||
response.setIssuer(issuer(issuerEntityId)); |
|
||||||
return response; |
|
||||||
} |
|
||||||
|
|
||||||
Issuer issuer(String entityId) { |
|
||||||
Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); |
|
||||||
issuer.setValue(entityId); |
|
||||||
return issuer; |
|
||||||
} |
|
||||||
|
|
||||||
<T extends XMLObject> T build(QName qName) { |
|
||||||
return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
@ -1,59 +0,0 @@ |
|||||||
/* |
|
||||||
* Copyright 2002-2021 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 org.junit.jupiter.api.BeforeEach; |
|
||||||
import org.junit.jupiter.api.Test; |
|
||||||
import org.opensaml.saml.saml2.core.LogoutRequest; |
|
||||||
import org.opensaml.xmlsec.signature.Signature; |
|
||||||
|
|
||||||
import org.springframework.security.saml2.core.TestSaml2X509Credentials; |
|
||||||
import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; |
|
||||||
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; |
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat; |
|
||||||
|
|
||||||
/** |
|
||||||
* Test open SAML Logout signatures |
|
||||||
*/ |
|
||||||
public class Saml2LogoutSigningUtilsTests { |
|
||||||
|
|
||||||
private RelyingPartyRegistration registration; |
|
||||||
|
|
||||||
@BeforeEach |
|
||||||
public void setup() { |
|
||||||
this.registration = RelyingPartyRegistration.withRegistrationId("saml-idp") |
|
||||||
.entityId("https://some.idp.example.com/entity-id") |
|
||||||
.signingX509Credentials((c) -> { |
|
||||||
c.add(TestSaml2X509Credentials.relyingPartySigningCredential()); |
|
||||||
c.add(TestSaml2X509Credentials.assertingPartySigningCredential()); |
|
||||||
}) |
|
||||||
.assertingPartyDetails((c) -> c.entityId("https://some.idp.example.com/entity-id") |
|
||||||
.singleSignOnServiceLocation("https://some.idp.example.com/service-location")) |
|
||||||
.build(); |
|
||||||
} |
|
||||||
|
|
||||||
@Test |
|
||||||
public void whenSigningLogoutRequestRPThenKeyInfoIsPartOfTheSignature() { |
|
||||||
LogoutRequest logoutRequest = TestOpenSamlObjects.relyingPartyLogoutRequest(this.registration); |
|
||||||
OpenSamlSigningUtils.sign(logoutRequest, this.registration); |
|
||||||
Signature signature = logoutRequest.getSignature(); |
|
||||||
assertThat(signature).isNotNull(); |
|
||||||
assertThat(signature.getKeyInfo()).isNotNull(); |
|
||||||
} |
|
||||||
|
|
||||||
} |
|
||||||
Loading…
Reference in new issue