Use OpenSAML API for web

Issue gh-11658
This commit is contained in:
Josh Cummings 2024-08-05 09:19:19 -06:00
parent bf5b334531
commit 78a0173cc1
No known key found for this signature in database
GPG Key ID: A306A51F43B8E5A5
13 changed files with 1576 additions and 239 deletions

View File

@ -39,7 +39,7 @@ import org.springframework.security.saml2.provider.service.registration.RelyingP
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrations;
import org.springframework.security.saml2.provider.service.web.HttpSessionSaml2AuthenticationRequestRepository;
import org.springframework.security.saml2.provider.service.web.OpenSamlAuthenticationTokenConverter;
import org.springframework.security.saml2.provider.service.web.OpenSaml4AuthenticationTokenConverter;
import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository;
import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationTokenConverter;
import org.springframework.security.saml2.provider.service.web.Saml2WebSsoAuthenticationRequestFilter;
@ -379,10 +379,10 @@ public final class Saml2LoginConfigurer<B extends HttpSecurityBuilder<B>>
AuthenticationConverter authenticationConverterBean = getBeanOrNull(http,
Saml2AuthenticationTokenConverter.class);
if (authenticationConverterBean == null) {
authenticationConverterBean = getBeanOrNull(http, OpenSamlAuthenticationTokenConverter.class);
authenticationConverterBean = getBeanOrNull(http, OpenSaml4AuthenticationTokenConverter.class);
}
if (authenticationConverterBean == null) {
OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(
this.relyingPartyRegistrationRepository);
converter.setAuthenticationRequestRepository(getAuthenticationRequestRepository(http));
converter.setRequestMatcher(this.loginProcessingUrl);

View File

@ -308,7 +308,7 @@ public class Saml2LoginConfigurerTests {
Saml2AuthenticationException exception = captor.getValue();
assertThat(exception.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE);
assertThat(exception.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string");
assertThat(exception.getCause()).isInstanceOf(IOException.class);
assertThat(exception).hasRootCauseInstanceOf(IOException.class);
}
@Test

View File

@ -38,6 +38,11 @@ sourceSets.configureEach { set ->
with from
}
copy {
into "$projectDir/src/$set.name/java/org/springframework/security/saml2/provider/service/web"
filter { line -> line.replaceAll(".saml2.internal", ".saml2.provider.service.web") }
with from
}
}
dependencies {

View File

@ -0,0 +1,190 @@
/*
* 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;
import jakarta.servlet.http.HttpServletRequest;
import org.opensaml.saml.saml2.core.Response;
import org.springframework.http.HttpMethod;
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.AbstractSaml2AuthenticationRequest;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver;
import org.springframework.security.web.authentication.AuthenticationConverter;
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;
final class BaseOpenSamlAuthenticationTokenConverter implements AuthenticationConverter {
static {
OpenSamlInitializationService.initialize();
}
private final OpenSamlOperations saml;
private final RelyingPartyRegistrationRepository registrations;
private RequestMatcher requestMatcher = new OrRequestMatcher(
new AntPathRequestMatcher("/login/saml2/sso/{registrationId}"),
new AntPathRequestMatcher("/login/saml2/sso"));
private Saml2AuthenticationRequestRepository<?> authenticationRequests = new HttpSessionSaml2AuthenticationRequestRepository();
/**
* Constructs a {@link BaseOpenSamlAuthenticationTokenConverter} given a repository
* for {@link RelyingPartyRegistration}s
* @param registrations the repository for {@link RelyingPartyRegistration}s
* {@link RelyingPartyRegistration}s
*/
BaseOpenSamlAuthenticationTokenConverter(RelyingPartyRegistrationRepository registrations,
OpenSamlOperations saml) {
Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null");
this.registrations = registrations;
this.saml = saml;
}
/**
* Resolve an authentication request from the given {@link HttpServletRequest}.
*
* <p>
* First uses the configured {@link RequestMatcher} to deduce whether an
* authentication request is being made and optionally for which
* {@code registrationId}.
*
* <p>
* If there is an associated {@code <saml2:AuthnRequest>}, then the
* {@code registrationId} is looked up and used.
*
* <p>
* If a {@code registrationId} is found in the request, then it is looked up and used.
* In that case, if none is found a {@link Saml2AuthenticationException} is thrown.
*
* <p>
* Finally, if no {@code registrationId} is found in the request, then the code
* attempts to resolve the {@link RelyingPartyRegistration} from the SAML Response's
* Issuer.
* @param request the HTTP request
* @return the {@link Saml2AuthenticationToken} authentication request
* @throws Saml2AuthenticationException if the {@link RequestMatcher} specifies a
* non-existent {@code registrationId}
*/
@Override
public Saml2AuthenticationToken convert(HttpServletRequest request) {
String serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
if (serialized == null) {
return null;
}
RequestMatcher.MatchResult result = this.requestMatcher.matcher(request);
if (!result.isMatch()) {
return null;
}
Saml2AuthenticationToken token = tokenByAuthenticationRequest(request);
if (token == null) {
token = tokenByRegistrationId(request, result);
}
if (token == null) {
token = tokenByEntityId(request);
}
return token;
}
private Saml2AuthenticationToken tokenByAuthenticationRequest(HttpServletRequest request) {
AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequests
.loadAuthenticationRequest(request);
if (authenticationRequest == null) {
return null;
}
String registrationId = authenticationRequest.getRelyingPartyRegistrationId();
RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId);
return tokenByRegistration(request, registration, authenticationRequest);
}
private Saml2AuthenticationToken tokenByRegistrationId(HttpServletRequest request,
RequestMatcher.MatchResult result) {
String registrationId = result.getVariables().get("registrationId");
if (registrationId == null) {
return null;
}
RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId);
return tokenByRegistration(request, registration, null);
}
private Saml2AuthenticationToken tokenByEntityId(HttpServletRequest request) {
Response response = this.saml.deserialize(decode(request));
String issuer = response.getIssuer().getValue();
RelyingPartyRegistration registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer);
return tokenByRegistration(request, registration, null);
}
private Saml2AuthenticationToken tokenByRegistration(HttpServletRequest request,
RelyingPartyRegistration registration, AbstractSaml2AuthenticationRequest authenticationRequest) {
if (registration == null) {
return null;
}
String decoded = decode(request);
UriResolver resolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration);
registration = registration.mutate()
.entityId(resolver.resolve(registration.getEntityId()))
.assertionConsumerServiceLocation(resolver.resolve(registration.getAssertionConsumerServiceLocation()))
.build();
return new Saml2AuthenticationToken(registration, decoded, authenticationRequest);
}
/**
* Use the given {@link Saml2AuthenticationRequestRepository} to load authentication
* request.
* @param authenticationRequestRepository the
* {@link Saml2AuthenticationRequestRepository} to use
*/
void setAuthenticationRequestRepository(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null");
this.authenticationRequests = authenticationRequestRepository;
}
/**
* Use the given {@link RequestMatcher} to match the request.
* @param requestMatcher the {@link RequestMatcher} to use
*/
void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
private String decode(HttpServletRequest request) {
String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
try {
return Saml2Utils.withEncoded(encoded)
.requireBase64(true)
.inflate(HttpMethod.GET.matches(request.getMethod()))
.decode();
}
catch (Exception ex) {
throw new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, ex.getMessage()),
ex);
}
}
}

View File

@ -0,0 +1,104 @@
/*
* 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;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository;
import org.springframework.security.web.authentication.AuthenticationConverter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.util.Assert;
/**
* An {@link AuthenticationConverter} that generates a {@link Saml2AuthenticationToken}
* appropriate for authenticated a SAML 2.0 Assertion against an
* {@link org.springframework.security.authentication.AuthenticationManager}.
*
* @author Josh Cummings
* @since 6.1
*/
public final class OpenSaml4AuthenticationTokenConverter implements AuthenticationConverter {
private final BaseOpenSamlAuthenticationTokenConverter delegate;
/**
* Constructs a {@link OpenSaml4AuthenticationTokenConverter} given a repository for
* {@link RelyingPartyRegistration}s
* @param registrations the repository for {@link RelyingPartyRegistration}s
* {@link RelyingPartyRegistration}s
*/
public OpenSaml4AuthenticationTokenConverter(RelyingPartyRegistrationRepository registrations) {
Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null");
this.delegate = new BaseOpenSamlAuthenticationTokenConverter(registrations, new OpenSaml4Template());
}
/**
* Resolve an authentication request from the given {@link HttpServletRequest}.
*
* <p>
* First uses the configured {@link RequestMatcher} to deduce whether an
* authentication request is being made and optionally for which
* {@code registrationId}.
*
* <p>
* If there is an associated {@code <saml2:AuthnRequest>}, then the
* {@code registrationId} is looked up and used.
*
* <p>
* If a {@code registrationId} is found in the request, then it is looked up and used.
* In that case, if none is found a {@link Saml2AuthenticationException} is thrown.
*
* <p>
* Finally, if no {@code registrationId} is found in the request, then the code
* attempts to resolve the {@link RelyingPartyRegistration} from the SAML Response's
* Issuer.
* @param request the HTTP request
* @return the {@link Saml2AuthenticationToken} authentication request
* @throws Saml2AuthenticationException if the {@link RequestMatcher} specifies a
* non-existent {@code registrationId}
*/
@Override
public Saml2AuthenticationToken convert(HttpServletRequest request) {
return this.delegate.convert(request);
}
/**
* Use the given {@link Saml2AuthenticationRequestRepository} to load authentication
* request.
* @param authenticationRequestRepository the
* {@link Saml2AuthenticationRequestRepository} to use
*/
public void setAuthenticationRequestRepository(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null");
this.delegate.setAuthenticationRequestRepository(authenticationRequestRepository);
}
/**
* Use the given {@link RequestMatcher} to match the request.
* @param requestMatcher the {@link RequestMatcher} to use
*/
public void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.delegate.setRequestMatcher(requestMatcher);
}
}

View File

@ -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;
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);
}
}
}
}
}

View File

@ -16,27 +16,12 @@
package org.springframework.security.saml2.provider.service.web;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.function.Function;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.utilities.java.support.xml.ParserPool;
import org.opensaml.core.config.ConfigurationService;
import org.opensaml.core.xml.config.XMLObjectProviderRegistry;
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
import org.opensaml.saml.saml2.core.Response;
import org.opensaml.saml.saml2.core.impl.ResponseUnmarshaller;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.springframework.http.HttpMethod;
import org.springframework.security.saml2.Saml2Exception;
import org.springframework.security.saml2.core.OpenSamlInitializationService;
import org.springframework.security.saml2.core.Saml2Error;
import org.springframework.security.saml2.core.Saml2ErrorCodes;
@ -60,18 +45,17 @@ import org.springframework.util.Assert;
*
* @author Josh Cummings
* @since 6.1
* @deprecated Please use a version-specific SAML 2.0 {@link AuthenticationConverter}
* instead such as {@code OpenSaml4AuthenticationTokenConverter}
*/
@Deprecated
public final class OpenSamlAuthenticationTokenConverter implements AuthenticationConverter {
static {
OpenSamlInitializationService.initialize();
}
// MimeDecoder allows extra line-breaks as well as other non-alphabet values.
// This matches the behaviour of the commons-codec decoder.
private static final Base64.Decoder BASE64 = Base64.getMimeDecoder();
private static final Base64Checker BASE_64_CHECKER = new Base64Checker();
private final OpenSamlOperations saml = new OpenSaml4Template();
private final RelyingPartyRegistrationRepository registrations;
@ -79,10 +63,6 @@ public final class OpenSamlAuthenticationTokenConverter implements Authenticatio
new AntPathRequestMatcher("/login/saml2/sso/{registrationId}"),
new AntPathRequestMatcher("/login/saml2/sso"));
private final ParserPool parserPool;
private final ResponseUnmarshaller unmarshaller;
private Function<HttpServletRequest, AbstractSaml2AuthenticationRequest> loader;
/**
@ -93,10 +73,6 @@ public final class OpenSamlAuthenticationTokenConverter implements Authenticatio
*/
public OpenSamlAuthenticationTokenConverter(RelyingPartyRegistrationRepository registrations) {
Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null");
XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class);
this.parserPool = registry.getParserPool();
this.unmarshaller = (ResponseUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory()
.getUnmarshaller(Response.DEFAULT_ELEMENT_NAME);
this.registrations = registrations;
this.loader = new HttpSessionSaml2AuthenticationRequestRepository()::loadAuthenticationRequest;
}
@ -167,9 +143,7 @@ public final class OpenSamlAuthenticationTokenConverter implements Authenticatio
}
private Saml2AuthenticationToken tokenByEntityId(HttpServletRequest request) {
String serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
String decoded = new String(samlDecode(serialized), StandardCharsets.UTF_8);
Response response = parse(decoded);
Response response = this.saml.deserialize(decode(request));
String issuer = response.getIssuer().getValue();
RelyingPartyRegistration registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer);
return tokenByRegistration(request, registration, null);
@ -180,8 +154,7 @@ public final class OpenSamlAuthenticationTokenConverter implements Authenticatio
if (registration == null) {
return null;
}
String serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
String decoded = inflateIfRequired(request, samlDecode(serialized));
String decoded = decode(request);
UriResolver resolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration);
registration = registration.mutate()
.entityId(resolver.resolve(registration.getEntityId()))
@ -215,102 +188,18 @@ public final class OpenSamlAuthenticationTokenConverter implements Authenticatio
return this.loader.apply(request);
}
private String inflateIfRequired(HttpServletRequest request, byte[] b) {
if (HttpMethod.GET.matches(request.getMethod())) {
return samlInflate(b);
}
return new String(b, StandardCharsets.UTF_8);
}
private byte[] samlDecode(String base64EncodedPayload) {
private String decode(HttpServletRequest request) {
String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
try {
BASE_64_CHECKER.checkAcceptable(base64EncodedPayload);
return BASE64.decode(base64EncodedPayload);
return Saml2Utils.withEncoded(encoded)
.requireBase64(true)
.inflate(HttpMethod.GET.matches(request.getMethod()))
.decode();
}
catch (Exception ex) {
throw new Saml2AuthenticationException(
new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Failed to decode SAMLResponse"), ex);
throw new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, ex.getMessage()),
ex);
}
}
private String samlInflate(byte[] b) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(out, new Inflater(true));
inflaterOutputStream.write(b);
inflaterOutputStream.finish();
return out.toString(StandardCharsets.UTF_8.name());
}
catch (Exception ex) {
throw new Saml2AuthenticationException(
new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Unable to inflate string"), ex);
}
}
private Response parse(String request) throws Saml2Exception {
try {
Document document = this.parserPool
.parse(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8)));
Element element = document.getDocumentElement();
return (Response) this.unmarshaller.unmarshall(element);
}
catch (Exception ex) {
throw new Saml2Exception("Failed to deserialize LogoutRequest", ex);
}
}
static class Base64Checker {
private static final int[] values = genValueMapping();
Base64Checker() {
}
private static int[] genValueMapping() {
byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.getBytes(StandardCharsets.ISO_8859_1);
int[] values = new int[256];
Arrays.fill(values, -1);
for (int i = 0; i < alphabet.length; i++) {
values[alphabet[i] & 0xff] = i;
}
return values;
}
boolean isAcceptable(String s) {
int goodChars = 0;
int lastGoodCharVal = -1;
// count number of characters from Base64 alphabet
for (int i = 0; i < s.length(); i++) {
int val = values[0xff & s.charAt(i)];
if (val != -1) {
lastGoodCharVal = val;
goodChars++;
}
}
// in cases of an incomplete final chunk, ensure the unused bits are zero
switch (goodChars % 4) {
case 0:
return true;
case 2:
return (lastGoodCharVal & 0b1111) == 0;
case 3:
return (lastGoodCharVal & 0b11) == 0;
default:
return false;
}
}
void checkAcceptable(String ins) {
if (!isAcceptable(ins)) {
throw new IllegalArgumentException("Unaccepted Encoding");
}
}
}
}

View File

@ -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;
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);
}
}

View File

@ -16,13 +16,7 @@
package org.springframework.security.saml2.provider.service.web;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.function.Function;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
import jakarta.servlet.http.HttpServletRequest;
@ -47,12 +41,6 @@ import org.springframework.util.Assert;
*/
public final class Saml2AuthenticationTokenConverter implements AuthenticationConverter {
// MimeDecoder allows extra line-breaks as well as other non-alphabet values.
// This matches the behaviour of the commons-codec decoder.
private static final Base64.Decoder BASE64 = Base64.getMimeDecoder();
private static final Base64Checker BASE_64_CHECKER = new Base64Checker();
private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver;
private Function<HttpServletRequest, AbstractSaml2AuthenticationRequest> loader;
@ -79,12 +67,10 @@ public final class Saml2AuthenticationTokenConverter implements AuthenticationCo
if (relyingPartyRegistration == null) {
return null;
}
String saml2Response = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
String saml2Response = decode(request);
if (saml2Response == null) {
return null;
}
byte[] b = samlDecode(saml2Response);
saml2Response = inflateIfRequired(request, b);
return new Saml2AuthenticationToken(relyingPartyRegistration, saml2Response, authenticationRequest);
}
@ -105,90 +91,21 @@ public final class Saml2AuthenticationTokenConverter implements AuthenticationCo
return this.loader.apply(request);
}
private String inflateIfRequired(HttpServletRequest request, byte[] b) {
if (HttpMethod.GET.matches(request.getMethod())) {
return samlInflate(b);
private String decode(HttpServletRequest request) {
String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
if (encoded == null) {
return null;
}
return new String(b, StandardCharsets.UTF_8);
}
private byte[] samlDecode(String base64EncodedPayload) {
try {
BASE_64_CHECKER.checkAcceptable(base64EncodedPayload);
return BASE64.decode(base64EncodedPayload);
return Saml2Utils.withEncoded(encoded)
.requireBase64(true)
.inflate(HttpMethod.GET.matches(request.getMethod()))
.decode();
}
catch (Exception ex) {
throw new Saml2AuthenticationException(
new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Failed to decode SAMLResponse"), ex);
throw new Saml2AuthenticationException(new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, ex.getMessage()),
ex);
}
}
private String samlInflate(byte[] b) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(out, new Inflater(true));
inflaterOutputStream.write(b);
inflaterOutputStream.finish();
return out.toString(StandardCharsets.UTF_8.name());
}
catch (Exception ex) {
throw new Saml2AuthenticationException(
new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Unable to inflate string"), ex);
}
}
static class Base64Checker {
private static final int[] values = genValueMapping();
Base64Checker() {
}
private static int[] genValueMapping() {
byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.getBytes(StandardCharsets.ISO_8859_1);
int[] values = new int[256];
Arrays.fill(values, -1);
for (int i = 0; i < alphabet.length; i++) {
values[alphabet[i] & 0xff] = i;
}
return values;
}
boolean isAcceptable(String s) {
int goodChars = 0;
int lastGoodCharVal = -1;
// count number of characters from Base64 alphabet
for (int i = 0; i < s.length(); i++) {
int val = values[0xff & s.charAt(i)];
if (val != -1) {
lastGoodCharVal = val;
goodChars++;
}
}
// in cases of an incomplete final chunk, ensure the unused bits are zero
switch (goodChars % 4) {
case 0:
return true;
case 2:
return (lastGoodCharVal & 0b1111) == 0;
case 3:
return (lastGoodCharVal & 0b11) == 0;
default:
return false;
}
}
void checkAcceptable(String ins) {
if (!isAcceptable(ins)) {
throw new IllegalArgumentException("Unaccepted Encoding");
}
}
}
}

View File

@ -0,0 +1,196 @@
/*
* 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;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
import org.springframework.security.saml2.Saml2Exception;
/**
* Utility methods for working with serialized SAML messages.
*
* For internal use only.
*
* @author Josh Cummings
*/
final class Saml2Utils {
private Saml2Utils() {
}
static String samlEncode(byte[] b) {
return Base64.getEncoder().encodeToString(b);
}
static byte[] samlDecode(String s) {
return Base64.getMimeDecoder().decode(s);
}
static byte[] samlDeflate(String s) {
try {
ByteArrayOutputStream b = new ByteArrayOutputStream();
DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(Deflater.DEFLATED, true));
deflater.write(s.getBytes(StandardCharsets.UTF_8));
deflater.finish();
return b.toByteArray();
}
catch (IOException ex) {
throw new Saml2Exception("Unable to deflate string", ex);
}
}
static String samlInflate(byte[] b) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InflaterOutputStream iout = new InflaterOutputStream(out, new Inflater(true));
iout.write(b);
iout.finish();
return new String(out.toByteArray(), StandardCharsets.UTF_8);
}
catch (IOException ex) {
throw new Saml2Exception("Unable to inflate string", ex);
}
}
static EncodingConfigurer withDecoded(String decoded) {
return new EncodingConfigurer(decoded);
}
static DecodingConfigurer withEncoded(String encoded) {
return new DecodingConfigurer(encoded);
}
static final class EncodingConfigurer {
private final String decoded;
private boolean deflate;
private EncodingConfigurer(String decoded) {
this.decoded = decoded;
}
EncodingConfigurer deflate(boolean deflate) {
this.deflate = deflate;
return this;
}
String encode() {
byte[] bytes = (this.deflate) ? Saml2Utils.samlDeflate(this.decoded)
: this.decoded.getBytes(StandardCharsets.UTF_8);
return Saml2Utils.samlEncode(bytes);
}
}
static final class DecodingConfigurer {
private static final Base64Checker BASE_64_CHECKER = new Base64Checker();
private final String encoded;
private boolean inflate;
private boolean requireBase64;
private DecodingConfigurer(String encoded) {
this.encoded = encoded;
}
DecodingConfigurer inflate(boolean inflate) {
this.inflate = inflate;
return this;
}
DecodingConfigurer requireBase64(boolean requireBase64) {
this.requireBase64 = requireBase64;
return this;
}
String decode() {
if (this.requireBase64) {
BASE_64_CHECKER.checkAcceptable(this.encoded);
}
byte[] bytes = Saml2Utils.samlDecode(this.encoded);
return (this.inflate) ? Saml2Utils.samlInflate(bytes) : new String(bytes, StandardCharsets.UTF_8);
}
static class Base64Checker {
private static final int[] values = genValueMapping();
Base64Checker() {
}
private static int[] genValueMapping() {
byte[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.getBytes(StandardCharsets.ISO_8859_1);
int[] values = new int[256];
Arrays.fill(values, -1);
for (int i = 0; i < alphabet.length; i++) {
values[alphabet[i] & 0xff] = i;
}
return values;
}
boolean isAcceptable(String s) {
int goodChars = 0;
int lastGoodCharVal = -1;
// count number of characters from Base64 alphabet
for (int i = 0; i < s.length(); i++) {
int val = values[0xff & s.charAt(i)];
if (val != -1) {
lastGoodCharVal = val;
goodChars++;
}
}
// in cases of an incomplete final chunk, ensure the unused bits are zero
switch (goodChars % 4) {
case 0:
return true;
case 2:
return (lastGoodCharVal & 0b1111) == 0;
case 3:
return (lastGoodCharVal & 0b11) == 0;
default:
return false;
}
}
void checkAcceptable(String ins) {
if (!isAcceptable(ins)) {
throw new IllegalArgumentException("Failed to decode SAMLResponse");
}
}
}
}
}

View File

@ -0,0 +1,246 @@
/*
* 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;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.saml.common.SignableSAMLObject;
import org.opensaml.saml.saml2.core.Response;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.saml2.core.Saml2ErrorCodes;
import org.springframework.security.saml2.core.Saml2ParameterNames;
import org.springframework.security.saml2.core.Saml2Utils;
import org.springframework.security.saml2.core.TestSaml2X509Credentials;
import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationToken;
import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects;
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 org.springframework.util.StreamUtils;
import org.springframework.web.util.UriUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
/**
* Tests for {@link OpenSaml4AuthenticationTokenConverter}
*/
@ExtendWith(MockitoExtension.class)
public final class OpenSaml4AuthenticationTokenConverterTests {
@Mock
RelyingPartyRegistrationRepository registrations;
private final OpenSamlOperations saml = new OpenSaml4Template();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build();
@Test
public void convertWhenSamlResponseThenToken() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE,
Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId())
.isEqualTo(this.registration.getRegistrationId());
}
@Test
public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "invalid");
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request))
.withCauseInstanceOf(IllegalArgumentException.class)
.satisfies(
(ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE))
.satisfies(
(ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Failed to decode SAMLResponse"));
}
@Test
public void convertWhenNoSamlResponseThenNull() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
assertThat(converter.convert(request)).isNull();
}
@Test
public void convertWhenNoMatchingRequestThenNull() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = new MockHttpServletRequest();
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "ignored");
assertThat(converter.convert(request)).isNull();
}
@Test
public void convertWhenNoRelyingPartyRegistrationThenNull() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
String response = Saml2Utils.samlEncode(serialize(signed(response())).getBytes(StandardCharsets.UTF_8));
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, response);
assertThat(converter.convert(request)).isNull();
}
@Test
public void convertWhenGetRequestThenInflates() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] deflated = Saml2Utils.samlDeflate("response");
String encoded = Saml2Utils.samlEncode(deflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId())
.isEqualTo(this.registration.getRegistrationId());
}
@Test
public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = get("/login/saml2/sso/" + this.registration.getRegistrationId());
byte[] invalidDeflated = "invalid".getBytes();
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request))
.withRootCauseInstanceOf(IOException.class)
.satisfies(
(ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE))
.satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
}
@Test
public void convertWhenUsingSamlUtilsBase64ThenXmlIsValid() throws Exception {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, getSsoCircleEncodedXml());
Saml2AuthenticationToken token = converter.convert(request);
validateSsoCircleXml(token.getSaml2Response());
}
@Test
public void convertWhenSavedAuthenticationRequestThenToken() {
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock(
Saml2AuthenticationRequestRepository.class);
AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class);
given(authenticationRequest.getRelyingPartyRegistrationId()).willReturn(this.registration.getRegistrationId());
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
converter.setAuthenticationRequestRepository(authenticationRequestRepository);
given(this.registrations.findByRegistrationId(any())).willReturn(this.registration);
given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class)))
.willReturn(authenticationRequest);
MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId());
request.setParameter(Saml2ParameterNames.SAML_RESPONSE,
Saml2Utils.samlEncode("response".getBytes(StandardCharsets.UTF_8)));
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo("response");
assertThat(token.getRelyingPartyRegistration().getRegistrationId())
.isEqualTo(this.registration.getRegistrationId());
assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest);
}
@Test
public void convertWhenMatchingNoRegistrationIdThenLooksUpByAssertingEntityId() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
String response = serialize(signed(response()));
String encoded = Saml2Utils.samlEncode(response.getBytes(StandardCharsets.UTF_8));
given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID))
.willReturn(this.registration);
MockHttpServletRequest request = post("/login/saml2/sso");
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
Saml2AuthenticationToken token = converter.convert(request);
assertThat(token.getSaml2Response()).isEqualTo(response);
assertThat(token.getRelyingPartyRegistration().getRegistrationId())
.isEqualTo(this.registration.getRegistrationId());
}
@Test
public void constructorWhenResolverIsNullThenIllegalArgument() {
assertThatIllegalArgumentException().isThrownBy(() -> new Saml2AuthenticationTokenConverter(null));
}
@Test
public void setAuthenticationRequestRepositoryWhenNullThenIllegalArgument() {
OpenSaml4AuthenticationTokenConverter converter = new OpenSaml4AuthenticationTokenConverter(this.registrations);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> converter.setAuthenticationRequestRepository(null));
}
private void validateSsoCircleXml(String xml) {
assertThat(xml).contains("InResponseTo=\"ARQ9a73ead-7dcf-45a8-89eb-26f3c9900c36\"")
.contains(" ID=\"s246d157446618e90e43fb79bdd4d9e9e19cf2c7c4\"")
.contains("<saml:Issuer>https://idp.ssocircle.com</saml:Issuer>");
}
private String getSsoCircleEncodedXml() throws IOException {
ClassPathResource resource = new ClassPathResource("saml2-response-sso-circle.encoded");
String response = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
return UriUtils.decode(response, StandardCharsets.UTF_8);
}
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 <T extends SignableSAMLObject> T signed(T toSign) {
TestOpenSamlObjects.signed(toSign, TestSaml2X509Credentials.assertingPartySigningCredential(),
TestOpenSamlObjects.RELYING_PARTY_ENTITY_ID);
return toSign;
}
private Response response() {
Response response = TestOpenSamlObjects.response();
response.setIssueInstant(Instant.now());
return response;
}
private String serialize(XMLObject object) {
return this.saml.serialize(object).serialize();
}
}

View File

@ -21,22 +21,16 @@ import java.nio.charset.StandardCharsets;
import java.time.Instant;
import jakarta.servlet.http.HttpServletRequest;
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.opensaml.core.xml.XMLObject;
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
import org.opensaml.core.xml.io.Marshaller;
import org.opensaml.core.xml.io.MarshallingException;
import org.opensaml.saml.common.SignableSAMLObject;
import org.opensaml.saml.saml2.core.Response;
import org.w3c.dom.Element;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.security.saml2.Saml2Exception;
import org.springframework.security.saml2.core.Saml2ErrorCodes;
import org.springframework.security.saml2.core.Saml2ParameterNames;
import org.springframework.security.saml2.core.Saml2Utils;
@ -67,6 +61,8 @@ public final class OpenSamlAuthenticationTokenConverterTests {
@Mock
RelyingPartyRegistrationRepository registrations;
private final OpenSamlOperations saml = new OpenSaml4Template();
RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build();
@Test
@ -143,7 +139,7 @@ public final class OpenSamlAuthenticationTokenConverterTests {
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request))
.withCauseInstanceOf(IOException.class)
.withRootCauseInstanceOf(IOException.class)
.satisfies(
(ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE))
.satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));
@ -244,14 +240,7 @@ public final class OpenSamlAuthenticationTokenConverterTests {
}
private String serialize(XMLObject object) {
try {
Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object);
Element element = marshaller.marshall(object);
return SerializeSupport.nodeToString(element);
}
catch (MarshallingException ex) {
throw new Saml2Exception(ex);
}
return this.saml.serialize(object).serialize();
}
}

View File

@ -151,7 +151,7 @@ public class Saml2AuthenticationTokenConverterTests {
String encoded = Saml2Utils.samlEncode(invalidDeflated);
request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded);
assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request))
.withCauseInstanceOf(IOException.class)
.withRootCauseInstanceOf(IOException.class)
.satisfies(
(ex) -> assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE))
.satisfies((ex) -> assertThat(ex.getSaml2Error().getDescription()).isEqualTo("Unable to inflate string"));