Skip to content

Add OpenSAML 4 support #9267

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions config/spring-security-config.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ apply plugin: 'io.spring.convention.spring-module'
apply plugin: 'trang'
apply plugin: 'kotlin'

repositories {
maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" }
}

dependencies {
// NB: Don't add other compile time dependencies to the config module as this breaks tooling
compile project(':spring-security-core')
Expand All @@ -14,7 +18,8 @@ dependencies {

optional project(':spring-security-ldap')
optional project(':spring-security-messaging')
optional project(':spring-security-saml2-service-provider')
optional project(':saml2-service-provider-opensaml3')
optional project(':saml2-service-provider-opensaml4')
optional project(':spring-security-oauth2-client')
optional project(':spring-security-oauth2-jose')
optional project(':spring-security-oauth2-resource-server')
Expand Down Expand Up @@ -42,7 +47,8 @@ dependencies {
testCompile project(path : ':spring-security-ldap', configuration : 'tests')
testCompile project(path : ':spring-security-oauth2-client', configuration : 'tests')
testCompile project(path : ':spring-security-oauth2-resource-server', configuration : 'tests')
testCompile project(path : ':spring-security-saml2-service-provider', configuration : 'tests')
testCompile project(path : ':saml2-service-provider-core', configuration : 'tests')
testCompile project(path : ':saml2-service-provider-opensaml4', configuration : 'tests')
testCompile project(path : ':spring-security-web', configuration : 'tests')
testCompile apachedsDependencies
testCompile powerMock2Dependencies
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,20 @@

import javax.servlet.Filter;

import org.opensaml.core.Version;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider;
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationRequestFactory;
import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationProvider;
import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationRequestFactory;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestFactory;
Expand Down Expand Up @@ -190,7 +195,7 @@ protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingU
* <li>The {@code loginProcessingUrl} is set</li>
* <li>A custom login page is configured, <b>or</b></li>
* <li>A default login page with all SAML 2.0 Identity Providers is configured</li>
* <li>An {@link OpenSamlAuthenticationProvider} is configured</li>
* <li>An {@link AuthenticationProvider} is configured</li>
* </ul>
*/
@Override
Expand Down Expand Up @@ -256,8 +261,12 @@ private AuthenticationConverter getAuthenticationConverter(B http) {
}

private void registerDefaultAuthenticationProvider(B http) {
OpenSamlAuthenticationProvider provider = postProcess(new OpenSamlAuthenticationProvider());
http.authenticationProvider(provider);
if (Version.getVersion().startsWith("4")) {
http.authenticationProvider(postProcess(new OpenSaml4AuthenticationProvider()));
}
else {
http.authenticationProvider(postProcess(new OpenSamlAuthenticationProvider()));
}
}

private void registerDefaultCsrfOverride(B http) {
Expand Down Expand Up @@ -337,7 +346,10 @@ private Filter build(B http) {
private Saml2AuthenticationRequestFactory getResolver(B http) {
Saml2AuthenticationRequestFactory resolver = getSharedOrBean(http, Saml2AuthenticationRequestFactory.class);
if (resolver == null) {
resolver = new OpenSamlAuthenticationRequestFactory();
if (Version.getVersion().startsWith("4")) {
return new OpenSaml4AuthenticationRequestFactory();
}
return new OpenSamlAuthenticationRequestFactory();
}
return resolver;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import java.io.IOException;
import java.net.URLDecoder;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -61,8 +62,9 @@
import org.springframework.security.saml2.core.Saml2ErrorCodes;
import org.springframework.security.saml2.core.Saml2Utils;
import org.springframework.security.saml2.core.TestSaml2X509Credentials;
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider;
import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationRequestFactory;
import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationProvider;
import org.springframework.security.saml2.provider.service.authentication.OpenSamlAuthenticationRequestFactory;
import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException;
import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationRequestContext;
Expand Down Expand Up @@ -235,11 +237,8 @@ private void validateSaml2WebSsoAuthenticationFilterConfiguration() {
"authenticationManager");
ProviderManager pm = (ProviderManager) manager;
AuthenticationProvider provider = pm.getProviders().stream()
.filter((p) -> p instanceof OpenSamlAuthenticationProvider).findFirst().get();
Assert.assertSame(AUTHORITIES_EXTRACTOR, ReflectionTestUtils.getField(provider, "authoritiesExtractor"));
Assert.assertSame(AUTHORITIES_MAPPER, ReflectionTestUtils.getField(provider, "authoritiesMapper"));
Assert.assertSame(RESPONSE_TIME_VALIDATION_SKEW,
ReflectionTestUtils.getField(provider, "responseTimeValidationSkew"));
.filter((p) -> p instanceof OpenSaml4AuthenticationProvider).findFirst().get();
assertThat(provider).isNotNull();
}

private Saml2WebSsoAuthenticationFilter getSaml2SsoFilter(FilterChainProxy chain) {
Expand Down Expand Up @@ -370,9 +369,10 @@ protected void configure(HttpSecurity http) throws Exception {

@Bean
Saml2AuthenticationRequestFactory authenticationRequestFactory() {
OpenSamlAuthenticationRequestFactory authenticationRequestFactory = new OpenSamlAuthenticationRequestFactory();
OpenSaml4AuthenticationRequestFactory authenticationRequestFactory = new OpenSaml4AuthenticationRequestFactory();
authenticationRequestFactory.setAuthenticationRequestContextConverter((context) -> {
AuthnRequest authnRequest = TestOpenSamlObjects.authnRequest();
authnRequest.setIssueInstant(Instant.now());
authnRequest.setForceAuthn(true);
return authnRequest;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
buildscript {
repositories {
maven { url 'https://repo.spring.io/plugins-release' }
}
dependencies {
classpath 'io.spring.gradle:propdeps-plugin:0.0.10.RELEASE'
}
}

plugins {
id 'java-library'
id 'io.spring.convention.repository'
id 'io.spring.convention.springdependencymangement'
id 'io.spring.convention.dependency-set'
id 'io.spring.convention.checkstyle'
id 'io.spring.convention.tests-configuration'
id 'io.spring.convention.integration-test'
id 'propdeps'
}

configurations {
classesOnlyElements {
canBeConsumed = true
canBeResolved = false
}
}

artifacts {
classesOnlyElements(compileJava.destinationDir)
}

repositories {
maven { url "https://build.shibboleth.net/nexus/content/repositories/releases/" }
}

dependencies {
constraints {
management("org.opensaml:opensaml-core:3.+")
management("org.opensaml:opensaml-saml-api:3.+")
management("org.opensaml:opensaml-saml-impl:3.+")
}

compile project(':spring-security-core')
compile project(':spring-security-web')

provided("org.opensaml:opensaml-core")
provided("org.opensaml:opensaml-saml-api")
provided("org.opensaml:opensaml-saml-impl")

provided 'javax.servlet:javax.servlet-api'

testCompile 'com.squareup.okhttp3:mockwebserver'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Copyright 2002-2020 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.core;

import java.time.Clock;
import java.time.Instant;
import java.util.UUID;

import org.joda.time.DateTime;
import org.opensaml.core.xml.XMLObjectBuilder;
import org.opensaml.saml.common.xml.SAMLConstants;
import org.opensaml.saml.saml2.core.AuthnRequest;
import org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder;

/**
* A {@link AuthnRequestBuilder} that gives each {@link AuthnRequest} some reasonable
* defaults.
*
* @author Josh Cummings
* @since 5.5
*/
public final class SpringSecurityAuthnRequestBuilder extends AuthnRequestBuilder {

private final XMLObjectBuilder<AuthnRequest> builder;

private Clock clock = Clock.systemUTC();

SpringSecurityAuthnRequestBuilder(XMLObjectBuilder<AuthnRequest> builder) {
this.builder = builder;
}

/** {@inheritDoc} */
@Override
public AuthnRequest buildObject(final String namespaceURI, final String localName, final String namespacePrefix) {
AuthnRequest authnRequest = this.builder.buildObject(namespaceURI, localName, namespacePrefix);
setDefaults(authnRequest);
return authnRequest;
}

/**
* Use this {@link Clock} with {@link Instant#now()} for generating timestamps
* @param clock
*/
public void setClock(Clock clock) {
this.clock = clock;
}

private void setDefaults(AuthnRequest authnRequest) {
if (authnRequest.getID() == null) {
authnRequest.setID("ARQ" + UUID.randomUUID().toString().substring(1));
}
if (authnRequest.getIssueInstant() == null) {
authnRequest.setIssueInstant(new DateTime(this.clock.millis()));
}
if (authnRequest.isForceAuthn() == null) {
authnRequest.setForceAuthn(Boolean.FALSE);
}
if (authnRequest.isPassive() == null) {
authnRequest.setIsPassive(Boolean.FALSE);
}
if (authnRequest.getProtocolBinding() == null) {
authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* 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.authentication;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

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.EncryptedAssertion;
import org.opensaml.saml.saml2.core.EncryptedAttribute;
import org.opensaml.saml.saml2.core.NameID;
import org.opensaml.saml.saml2.core.Response;
import org.opensaml.saml.saml2.encryption.Decrypter;
import org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver;
import org.opensaml.security.credential.Credential;
import org.opensaml.security.credential.CredentialSupport;
import org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver;
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.keyinfo.KeyInfoCredentialResolver;
import org.opensaml.xmlsec.keyinfo.impl.CollectionKeyInfoCredentialResolver;

import org.springframework.security.saml2.Saml2Exception;
import org.springframework.security.saml2.core.Saml2X509Credential;
import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration;

/**
* Utility methods for decrypting SAML components with OpenSAML
*
* For internal use only.
*
* @author Josh Cummings
*/
final class OpenSamlDecryptionUtils {

private static final EncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(
Arrays.asList(new InlineEncryptedKeyResolver(), new EncryptedElementTypeEncryptedKeyResolver(),
new SimpleRetrievalMethodEncryptedKeyResolver()));

static void decryptResponseElements(Response response, RelyingPartyRegistration registration) {
Decrypter decrypter = decrypter(registration);
for (EncryptedAssertion encryptedAssertion : response.getEncryptedAssertions()) {
try {
Assertion assertion = decrypter.decrypt(encryptedAssertion);
response.getAssertions().add(assertion);
}
catch (Exception ex) {
throw new Saml2Exception(ex);
}
}
}

static void decryptAssertionElements(Assertion assertion, RelyingPartyRegistration registration) {
Decrypter decrypter = decrypter(registration);
for (AttributeStatement statement : assertion.getAttributeStatements()) {
for (EncryptedAttribute encryptedAttribute : statement.getEncryptedAttributes()) {
try {
Attribute attribute = decrypter.decrypt(encryptedAttribute);
statement.getAttributes().add(attribute);
}
catch (Exception ex) {
throw new Saml2Exception(ex);
}
}
}
if (assertion.getSubject() == null) {
return;
}
if (assertion.getSubject().getEncryptedID() == null) {
return;
}
try {
assertion.getSubject().setNameID((NameID) decrypter.decrypt(assertion.getSubject().getEncryptedID()));
}
catch (Exception ex) {
throw new Saml2Exception(ex);
}
}

private static Decrypter decrypter(RelyingPartyRegistration registration) {
Collection<Credential> credentials = new ArrayList<>();
for (Saml2X509Credential key : registration.getDecryptionX509Credentials()) {
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;
}

private OpenSamlDecryptionUtils() {
}

}
Loading