HttpSecurity.saml2login() - MVP Core Code
Implements minimal SAML 2.0 login/authentication functionality with the
following feature set:
- Supports IDP initiated login at the default url of /login/saml2/sso/{registrationId}
- Supports SP initiated login at the default url of /saml2/authenticate/{registrationId}
- Supports basic java-configuration via DSL
- Provides an integration sample using Spring Boot
Not implemented with this MVP
- Single Logout
- Dynamic Service Provider Metadata
Fixes gh-6019
This commit is contained in:
44
samples/boot/saml2login/README.adoc
Normal file
44
samples/boot/saml2login/README.adoc
Normal file
@@ -0,0 +1,44 @@
|
||||
= OAuth 2.0 Login Sample
|
||||
|
||||
This guide provides instructions on setting up the sample application with SAML 2.0 Login using
|
||||
Spring Security's `saml2Login()` feature.
|
||||
|
||||
The sample application uses Spring Boot 2.2.0.M5 and the `spring-security-saml2-service-provider`
|
||||
module which is new in Spring Security 5.2.
|
||||
|
||||
== Goals
|
||||
|
||||
`saml2Login()` provides a very simple, basic, implementation of a Service Provider
|
||||
that can receive a SAML 2 Response XML object via the HTTP-POST and HTTP-REDIRECT bindings
|
||||
against a known SAML reference implementation by SimpleSAMLPhp.
|
||||
|
||||
|
||||
The following features are implemented in the MVP
|
||||
|
||||
1. Receive and validate a SAML 2.0 Response object containing an assertion
|
||||
and create a valid authentication in Spring Security
|
||||
2. Send a SAML 2 AuthNRequest object to an Identity Provider
|
||||
3. Provide a framework for components used in SAML 2.0 authentication that can
|
||||
be swapped by configuration
|
||||
4. Sample working against the SimpleSAMLPhP reference implementation
|
||||
|
||||
== Run the Sample
|
||||
|
||||
=== Start up the Sample Boot Application
|
||||
```
|
||||
./gradlew :spring-security-samples-boot-saml2login:bootRun
|
||||
```
|
||||
|
||||
=== Open a Browser
|
||||
|
||||
http://localhost:8080/
|
||||
|
||||
You will be redirect to the SimpleSAMLPhp IDP
|
||||
|
||||
=== Type in your credentials
|
||||
|
||||
```
|
||||
User: user
|
||||
Password: password
|
||||
```
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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.
|
||||
*/
|
||||
|
||||
apply plugin: 'io.spring.convention.spring-sample-boot'
|
||||
|
||||
dependencies {
|
||||
compile project(':spring-security-config')
|
||||
compile project(':spring-security-saml2-service-provider')
|
||||
compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
|
||||
compile 'org.springframework.boot:spring-boot-starter-web'
|
||||
compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
|
||||
|
||||
testCompile project(':spring-security-test')
|
||||
testCompile 'net.sourceforge.htmlunit:htmlunit'
|
||||
testCompile 'org.springframework.boot:spring-boot-starter-test'
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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.samples;
|
||||
|
||||
import org.springframework.security.saml2.Saml2Exception;
|
||||
|
||||
import net.shibboleth.utilities.java.support.annotation.constraint.NotEmpty;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.xml.security.algorithms.JCEMapper;
|
||||
import org.apache.xml.security.encryption.XMLCipherParameters;
|
||||
import org.joda.time.DateTime;
|
||||
import org.joda.time.Duration;
|
||||
import org.junit.Assert;
|
||||
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
|
||||
import org.opensaml.profile.action.EventIds;
|
||||
import org.opensaml.profile.context.EventContext;
|
||||
import org.opensaml.profile.context.ProfileRequestContext;
|
||||
import org.opensaml.saml.common.SAMLObjectBuilder;
|
||||
import org.opensaml.saml.common.SAMLVersion;
|
||||
import org.opensaml.saml.saml2.core.Artifact;
|
||||
import org.opensaml.saml.saml2.core.ArtifactResolve;
|
||||
import org.opensaml.saml.saml2.core.ArtifactResponse;
|
||||
import org.opensaml.saml.saml2.core.Assertion;
|
||||
import org.opensaml.saml.saml2.core.AttributeQuery;
|
||||
import org.opensaml.saml.saml2.core.AttributeStatement;
|
||||
import org.opensaml.saml.saml2.core.AuthnRequest;
|
||||
import org.opensaml.saml.saml2.core.AuthnStatement;
|
||||
import org.opensaml.saml.saml2.core.Conditions;
|
||||
import org.opensaml.saml.saml2.core.EncryptedAssertion;
|
||||
import org.opensaml.saml.saml2.core.EncryptedID;
|
||||
import org.opensaml.saml.saml2.core.Issuer;
|
||||
import org.opensaml.saml.saml2.core.LogoutRequest;
|
||||
import org.opensaml.saml.saml2.core.LogoutResponse;
|
||||
import org.opensaml.saml.saml2.core.NameID;
|
||||
import org.opensaml.saml.saml2.core.Response;
|
||||
import org.opensaml.saml.saml2.core.Subject;
|
||||
import org.opensaml.saml.saml2.core.SubjectConfirmation;
|
||||
import org.opensaml.saml.saml2.core.SubjectConfirmationData;
|
||||
import org.opensaml.saml.saml2.encryption.Encrypter;
|
||||
import org.opensaml.security.credential.BasicCredential;
|
||||
import org.opensaml.security.credential.Credential;
|
||||
import org.opensaml.security.credential.CredentialSupport;
|
||||
import org.opensaml.xmlsec.encryption.support.DataEncryptionParameters;
|
||||
import org.opensaml.xmlsec.encryption.support.EncryptionException;
|
||||
import org.opensaml.xmlsec.encryption.support.KeyEncryptionParameters;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.NoSuchProviderException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.zip.Deflater;
|
||||
import java.util.zip.DeflaterOutputStream;
|
||||
import java.util.zip.Inflater;
|
||||
import java.util.zip.InflaterOutputStream;
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
import javax.crypto.SecretKey;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.zip.Deflater.DEFLATED;
|
||||
import static org.opensaml.security.crypto.KeySupport.generateKey;
|
||||
|
||||
/**
|
||||
* <b>Copied from OpenSAML Source Code</b> Helper methods for creating/testing SAML 2
|
||||
* objects within profile action tests. When methods herein refer to mock objects they are
|
||||
* always objects that have been created via Mockito unless otherwise noted.
|
||||
*/
|
||||
public class OpenSamlActionTestingSupport {
|
||||
|
||||
static Base64 UNCHUNKED_ENCODER = new Base64(0, new byte[] { '\n' });
|
||||
|
||||
/** ID used for all generated {@link Response} objects. */
|
||||
final static String REQUEST_ID = "request";
|
||||
|
||||
/** ID used for all generated {@link Response} objects. */
|
||||
final static String RESPONSE_ID = "response";
|
||||
|
||||
/** ID used for all generated {@link Assertion} objects. */
|
||||
final static String ASSERTION_ID = "assertion";
|
||||
|
||||
static String encode(byte[] b) {
|
||||
return UNCHUNKED_ENCODER.encodeToString(b);
|
||||
}
|
||||
|
||||
static byte[] decode(String s) {
|
||||
return UNCHUNKED_ENCODER.decode(s);
|
||||
}
|
||||
|
||||
static byte[] deflate(String s) {
|
||||
try {
|
||||
ByteArrayOutputStream b = new ByteArrayOutputStream();
|
||||
DeflaterOutputStream deflater = new DeflaterOutputStream(b, new Deflater(DEFLATED, true));
|
||||
deflater.write(s.getBytes(UTF_8));
|
||||
deflater.finish();
|
||||
return b.toByteArray();
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new Saml2Exception("Unable to deflate string", e);
|
||||
}
|
||||
}
|
||||
|
||||
static String inflate(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(), UTF_8);
|
||||
}
|
||||
catch (IOException e) {
|
||||
throw new Saml2Exception("Unable to inflate string", e);
|
||||
}
|
||||
}
|
||||
|
||||
static EncryptedAssertion encryptAssertion(Assertion assertion, X509Certificate certificate) {
|
||||
Encrypter encrypter = getEncrypter(certificate);
|
||||
try {
|
||||
Encrypter.KeyPlacement keyPlacement = Encrypter.KeyPlacement.valueOf("PEER");
|
||||
encrypter.setKeyPlacement(keyPlacement);
|
||||
return encrypter.encrypt(assertion);
|
||||
}
|
||||
catch (EncryptionException e) {
|
||||
throw new Saml2Exception("Unable to encrypt assertion.", e);
|
||||
}
|
||||
}
|
||||
|
||||
static EncryptedID encryptNameId(NameID nameID, X509Certificate certificate) {
|
||||
Encrypter encrypter = getEncrypter(certificate);
|
||||
try {
|
||||
Encrypter.KeyPlacement keyPlacement = Encrypter.KeyPlacement.valueOf("PEER");
|
||||
encrypter.setKeyPlacement(keyPlacement);
|
||||
return encrypter.encrypt(nameID);
|
||||
}
|
||||
catch (EncryptionException e) {
|
||||
throw new Saml2Exception("Unable to encrypt nameID.", e);
|
||||
}
|
||||
}
|
||||
|
||||
static Encrypter getEncrypter(X509Certificate certificate) {
|
||||
Credential credential = CredentialSupport.getSimpleCredential(certificate, null);
|
||||
final String dataAlgorithm = XMLCipherParameters.AES_256;
|
||||
final String keyAlgorithm = XMLCipherParameters.RSA_1_5;
|
||||
SecretKey secretKey = generateKeyFromURI(dataAlgorithm);
|
||||
BasicCredential dataCredential = new BasicCredential(secretKey);
|
||||
DataEncryptionParameters dataEncryptionParameters = new DataEncryptionParameters();
|
||||
dataEncryptionParameters.setEncryptionCredential(dataCredential);
|
||||
dataEncryptionParameters.setAlgorithm(dataAlgorithm);
|
||||
|
||||
KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters();
|
||||
keyEncryptionParameters.setEncryptionCredential(credential);
|
||||
keyEncryptionParameters.setAlgorithm(keyAlgorithm);
|
||||
|
||||
Encrypter encrypter = new Encrypter(dataEncryptionParameters, asList(keyEncryptionParameters));
|
||||
|
||||
return encrypter;
|
||||
}
|
||||
|
||||
static SecretKey generateKeyFromURI(String algoURI) {
|
||||
try {
|
||||
String jceAlgorithmName = JCEMapper.getJCEKeyAlgorithmFromURI(algoURI);
|
||||
int keyLength = JCEMapper.getKeyLengthFromURI(algoURI);
|
||||
return generateKey(jceAlgorithmName, keyLength, null);
|
||||
}
|
||||
catch (NoSuchAlgorithmException | NoSuchProviderException e) {
|
||||
throw new Saml2Exception(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an empty response. The ID of the message is {@link #OUTBOUND_MSG_ID}, the
|
||||
* issue instant is 1970-01-01T00:00:00Z and the SAML version is
|
||||
* {@link SAMLVersion#VERSION_11}.
|
||||
* @return the constructed response
|
||||
*/
|
||||
@Nonnull
|
||||
static Response buildResponse() {
|
||||
final SAMLObjectBuilder<Response> responseBuilder = (SAMLObjectBuilder<Response>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Response>getBuilderOrThrow(Response.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final Response response = responseBuilder.buildObject();
|
||||
response.setID(OUTBOUND_MSG_ID);
|
||||
response.setIssueInstant(DateTime.now());
|
||||
response.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an empty artifact response. The ID of the message is
|
||||
* {@link #OUTBOUND_MSG_ID}, the issue instant is 1970-01-01T00:00:00Z and the SAML
|
||||
* version is {@link SAMLVersion#VERSION_11}.
|
||||
* @return the constructed response
|
||||
*/
|
||||
@Nonnull
|
||||
static ArtifactResponse buildArtifactResponse() {
|
||||
final SAMLObjectBuilder<ArtifactResponse> responseBuilder = (SAMLObjectBuilder<ArtifactResponse>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<ArtifactResponse>getBuilderOrThrow(ArtifactResponse.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final ArtifactResponse response = responseBuilder.buildObject();
|
||||
response.setID(OUTBOUND_MSG_ID);
|
||||
response.setIssueInstant(DateTime.now());
|
||||
response.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an {@link LogoutRequest}. If a {@link NameID} is given, it will be added to
|
||||
* the constructed {@link LogoutRequest}.
|
||||
* @param name the NameID to add to the request
|
||||
* @return the built request
|
||||
*/
|
||||
@Nonnull
|
||||
static LogoutRequest buildLogoutRequest(final @Nullable NameID name) {
|
||||
final SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Issuer>getBuilderOrThrow(Issuer.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final SAMLObjectBuilder<LogoutRequest> reqBuilder = (SAMLObjectBuilder<LogoutRequest>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<LogoutRequest>getBuilderOrThrow(LogoutRequest.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final Issuer issuer = issuerBuilder.buildObject();
|
||||
issuer.setValue(INBOUND_MSG_ISSUER);
|
||||
|
||||
final LogoutRequest req = reqBuilder.buildObject();
|
||||
req.setID(REQUEST_ID);
|
||||
req.setIssueInstant(DateTime.now());
|
||||
req.setIssuer(issuer);
|
||||
req.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
if (name != null) {
|
||||
req.setNameID(name);
|
||||
}
|
||||
|
||||
return req;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an empty logout response. The ID of the message is {@link #OUTBOUND_MSG_ID},
|
||||
* the issue instant is 1970-01-01T00:00:00Z and the SAML version is
|
||||
* {@link SAMLVersion#VERSION_11}.
|
||||
* @return the constructed response
|
||||
*/
|
||||
@Nonnull
|
||||
static LogoutResponse buildLogoutResponse() {
|
||||
final SAMLObjectBuilder<LogoutResponse> responseBuilder = (SAMLObjectBuilder<LogoutResponse>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<LogoutResponse>getBuilderOrThrow(LogoutResponse.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final LogoutResponse response = responseBuilder.buildObject();
|
||||
response.setID(OUTBOUND_MSG_ID);
|
||||
response.setIssueInstant(DateTime.now());
|
||||
response.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an empty assertion. The ID of the message is {@link #ASSERTION_ID}, the
|
||||
* issue instant is 1970-01-01T00:00:00Z and the SAML version is
|
||||
* {@link SAMLVersion#VERSION_11}.
|
||||
* @return the constructed assertion
|
||||
*/
|
||||
@Nonnull
|
||||
static Assertion buildAssertion() {
|
||||
final SAMLObjectBuilder<Assertion> assertionBuilder = (SAMLObjectBuilder<Assertion>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Assertion>getBuilderOrThrow(Assertion.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final Assertion assertion = assertionBuilder.buildObject();
|
||||
assertion.setID(ASSERTION_ID);
|
||||
assertion.setIssueInstant(DateTime.now());
|
||||
assertion.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
return assertion;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
static SubjectConfirmation buildSubjectConfirmation() {
|
||||
final SAMLObjectBuilder<SubjectConfirmation> subjectConfirmation = (SAMLObjectBuilder<SubjectConfirmation>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<SubjectConfirmation>getBuilderOrThrow(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
return subjectConfirmation.buildObject();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an authentication statement. The authn instant is set to
|
||||
* 1970-01-01T00:00:00Z.
|
||||
* @return the constructed statement
|
||||
*/
|
||||
@Nonnull
|
||||
static AuthnStatement buildAuthnStatement() {
|
||||
final SAMLObjectBuilder<AuthnStatement> statementBuilder = (SAMLObjectBuilder<AuthnStatement>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<AuthnStatement>getBuilderOrThrow(AuthnStatement.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final AuthnStatement statement = statementBuilder.buildObject();
|
||||
statement.setAuthnInstant(DateTime.now());
|
||||
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an empty attribute statement.
|
||||
* @return the constructed statement
|
||||
*/
|
||||
@Nonnull
|
||||
static AttributeStatement buildAttributeStatement() {
|
||||
final SAMLObjectBuilder<AttributeStatement> statementBuilder = (SAMLObjectBuilder<AttributeStatement>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<AttributeStatement>getBuilderOrThrow(AttributeStatement.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final AttributeStatement statement = statementBuilder.buildObject();
|
||||
|
||||
return statement;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a {@link Subject}. If a principal name is given a {@link NameID}, whose
|
||||
* value is the given principal name, will be created and added to the
|
||||
* {@link Subject}.
|
||||
* @param principalName the principal name to add to the subject
|
||||
* @return the built subject
|
||||
*/
|
||||
@Nonnull
|
||||
static Subject buildSubject(final @Nullable String principalName) {
|
||||
final SAMLObjectBuilder<Subject> subjectBuilder = (SAMLObjectBuilder<Subject>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Subject>getBuilderOrThrow(Subject.DEFAULT_ELEMENT_NAME);
|
||||
final Subject subject = subjectBuilder.buildObject();
|
||||
|
||||
if (principalName != null) {
|
||||
subject.setNameID(buildNameID(principalName));
|
||||
}
|
||||
|
||||
return subject;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
static SubjectConfirmationData buildSubjectConfirmationData(String localSpEntityId) {
|
||||
final SAMLObjectBuilder<SubjectConfirmationData> subjectBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory()
|
||||
.<SubjectConfirmationData>getBuilderOrThrow(SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
|
||||
final SubjectConfirmationData subject = subjectBuilder.buildObject();
|
||||
subject.setRecipient(localSpEntityId);
|
||||
subject.setNotBefore(DateTime.now().minus(Duration.millis(5 * 60 * 1000)));
|
||||
subject.setNotOnOrAfter(DateTime.now().plus(Duration.millis(5 * 60 * 1000)));
|
||||
return subject;
|
||||
}
|
||||
|
||||
@Nonnull
|
||||
static Conditions buildConditions() {
|
||||
final SAMLObjectBuilder<Conditions> subjectBuilder = (SAMLObjectBuilder<Conditions>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Conditions>getBuilderOrThrow(Conditions.DEFAULT_ELEMENT_NAME);
|
||||
final Conditions conditions = subjectBuilder.buildObject();
|
||||
conditions.setNotBefore(DateTime.now().minus(Duration.millis(5 * 60 * 1000)));
|
||||
conditions.setNotOnOrAfter(DateTime.now().plus(Duration.millis(5 * 60 * 1000)));
|
||||
return conditions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a {@link NameID}.
|
||||
* @param principalName the principal name to use in the NameID
|
||||
* @return the built NameID
|
||||
*/
|
||||
@Nonnull
|
||||
static NameID buildNameID(final @Nonnull @NotEmpty String principalName) {
|
||||
final SAMLObjectBuilder<NameID> nameIdBuilder = (SAMLObjectBuilder<NameID>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<NameID>getBuilderOrThrow(NameID.DEFAULT_ELEMENT_NAME);
|
||||
final NameID nameId = nameIdBuilder.buildObject();
|
||||
nameId.setValue(principalName);
|
||||
return nameId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a {@link Issuer}.
|
||||
* @param entityID the entity ID to use in the Issuer
|
||||
* @return the built Issuer
|
||||
*/
|
||||
@Nonnull
|
||||
static Issuer buildIssuer(final @Nonnull @NotEmpty String entityID) {
|
||||
final SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Issuer>getBuilderOrThrow(Issuer.DEFAULT_ELEMENT_NAME);
|
||||
final Issuer issuer = issuerBuilder.buildObject();
|
||||
issuer.setValue(entityID);
|
||||
return issuer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an {@link AttributeQuery}. If a {@link Subject} is given, it will be added
|
||||
* to the constructed {@link AttributeQuery}.
|
||||
* @param subject the subject to add to the query
|
||||
* @return the built query
|
||||
*/
|
||||
@Nonnull
|
||||
static AttributeQuery buildAttributeQueryRequest(final @Nullable Subject subject) {
|
||||
final SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Issuer>getBuilderOrThrow(Issuer.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final SAMLObjectBuilder<AttributeQuery> queryBuilder = (SAMLObjectBuilder<AttributeQuery>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<AttributeQuery>getBuilderOrThrow(AttributeQuery.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final Issuer issuer = issuerBuilder.buildObject();
|
||||
issuer.setValue(INBOUND_MSG_ISSUER);
|
||||
|
||||
final AttributeQuery query = queryBuilder.buildObject();
|
||||
query.setID(REQUEST_ID);
|
||||
query.setIssueInstant(DateTime.now());
|
||||
query.setIssuer(issuer);
|
||||
query.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
if (subject != null) {
|
||||
query.setSubject(subject);
|
||||
}
|
||||
|
||||
return query;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an {@link AuthnRequest}.
|
||||
* @return the built request
|
||||
*/
|
||||
@Nonnull
|
||||
static AuthnRequest buildAuthnRequest() {
|
||||
final SAMLObjectBuilder<Issuer> issuerBuilder = (SAMLObjectBuilder<Issuer>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Issuer>getBuilderOrThrow(Issuer.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final SAMLObjectBuilder<AuthnRequest> requestBuilder = (SAMLObjectBuilder<AuthnRequest>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<AuthnRequest>getBuilderOrThrow(AuthnRequest.DEFAULT_ELEMENT_NAME);
|
||||
|
||||
final Issuer issuer = issuerBuilder.buildObject();
|
||||
issuer.setValue(INBOUND_MSG_ISSUER);
|
||||
|
||||
final AuthnRequest request = requestBuilder.buildObject();
|
||||
request.setID(REQUEST_ID);
|
||||
request.setIssueInstant(DateTime.now());
|
||||
request.setIssuer(issuer);
|
||||
request.setVersion(SAMLVersion.VERSION_20);
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a {@link ArtifactResolve}.
|
||||
* @param artifact the artifact to add to the request
|
||||
* @return the built request
|
||||
*/
|
||||
@Nonnull
|
||||
static ArtifactResolve buildArtifactResolve(final @Nullable String artifact) {
|
||||
final SAMLObjectBuilder<ArtifactResolve> requestBuilder = (SAMLObjectBuilder<ArtifactResolve>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<ArtifactResolve>getBuilderOrThrow(ArtifactResolve.DEFAULT_ELEMENT_NAME);
|
||||
final ArtifactResolve request = requestBuilder.buildObject();
|
||||
request.setID(REQUEST_ID);
|
||||
request.setIssueInstant(DateTime.now());
|
||||
request.setVersion(SAMLVersion.VERSION_11);
|
||||
|
||||
if (artifact != null) {
|
||||
final SAMLObjectBuilder<Artifact> artifactBuilder = (SAMLObjectBuilder<Artifact>) XMLObjectProviderRegistrySupport
|
||||
.getBuilderFactory().<Artifact>getBuilderOrThrow(Artifact.DEFAULT_ELEMENT_NAME);
|
||||
final Artifact art = artifactBuilder.buildObject();
|
||||
art.setArtifact(artifact);
|
||||
request.setArtifact(art);
|
||||
}
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
/** ID of the inbound message. */
|
||||
public final static String INBOUND_MSG_ID = "inbound";
|
||||
|
||||
/** Issuer of the inbound message. */
|
||||
public final static String INBOUND_MSG_ISSUER = "http://sp.example.org";
|
||||
|
||||
/** ID of the outbound message. */
|
||||
public final static String OUTBOUND_MSG_ID = "outbound";
|
||||
|
||||
/** Issuer of the outbound message. */
|
||||
public final static String OUTBOUND_MSG_ISSUER = "http://idp.example.org";
|
||||
|
||||
/**
|
||||
* Checks that the request context contains an EventContext, and that the event
|
||||
* content is as given.
|
||||
* @param profileRequestContext the context to check
|
||||
* @param event event to check
|
||||
*/
|
||||
static void assertEvent(@Nonnull final ProfileRequestContext profileRequestContext,
|
||||
@Nonnull final Object event) {
|
||||
EventContext ctx = profileRequestContext.getSubcontext(EventContext.class);
|
||||
Assert.assertNotNull(ctx);
|
||||
Assert.assertEquals(ctx.getEvent(), event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the given request context does not contain an EventContext (thus
|
||||
* signaling a "proceed" event).
|
||||
* @param profileRequestContext the context to check
|
||||
*/
|
||||
static void assertProceedEvent(@Nonnull final ProfileRequestContext profileRequestContext) {
|
||||
EventContext<String> ctx = profileRequestContext.getSubcontext(EventContext.class);
|
||||
Assert.assertTrue(ctx == null || ctx.getEvent().equals(EventIds.PROCEED_EVENT_ID));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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.samples;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.SpringBootConfiguration;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.ResultActions;
|
||||
|
||||
import net.shibboleth.utilities.java.support.xml.SerializeSupport;
|
||||
import org.joda.time.DateTime;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.opensaml.core.xml.XMLObject;
|
||||
import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
|
||||
import org.opensaml.core.xml.io.MarshallerFactory;
|
||||
import org.opensaml.core.xml.io.MarshallingException;
|
||||
import org.opensaml.saml.common.SignableSAMLObject;
|
||||
import org.opensaml.saml.saml2.core.Assertion;
|
||||
import org.opensaml.saml.saml2.core.EncryptedAssertion;
|
||||
import org.opensaml.saml.saml2.core.EncryptedID;
|
||||
import org.opensaml.saml.saml2.core.Response;
|
||||
import org.opensaml.saml.saml2.core.SubjectConfirmation;
|
||||
import org.opensaml.saml.saml2.core.SubjectConfirmationData;
|
||||
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.security.crypto.KeySupport;
|
||||
import org.opensaml.xmlsec.SignatureSigningParameters;
|
||||
import org.opensaml.xmlsec.signature.support.SignatureConstants;
|
||||
import org.opensaml.xmlsec.signature.support.SignatureException;
|
||||
import org.opensaml.xmlsec.signature.support.SignatureSupport;
|
||||
import org.w3c.dom.Element;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.KeyException;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.PublicKey;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.UUID;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.startsWith;
|
||||
import static org.springframework.security.samples.OpenSamlActionTestingSupport.buildConditions;
|
||||
import static org.springframework.security.samples.OpenSamlActionTestingSupport.buildIssuer;
|
||||
import static org.springframework.security.samples.OpenSamlActionTestingSupport.buildSubject;
|
||||
import static org.springframework.security.samples.OpenSamlActionTestingSupport.buildSubjectConfirmation;
|
||||
import static org.springframework.security.samples.OpenSamlActionTestingSupport.buildSubjectConfirmationData;
|
||||
import static org.springframework.security.samples.OpenSamlActionTestingSupport.encryptNameId;
|
||||
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
|
||||
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@AutoConfigureMockMvc
|
||||
public class Saml2LoginIntegrationTests {
|
||||
|
||||
static final String LOCAL_SP_ENTITY_ID = "http://localhost:8080/saml2/service-provider-metadata/simplesamlphp";
|
||||
|
||||
@Autowired
|
||||
MockMvc mockMvc;
|
||||
|
||||
@SpringBootConfiguration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan(basePackages = "sample")
|
||||
public static class SpringBootApplicationTestConfig {
|
||||
}
|
||||
|
||||
@Test
|
||||
public void redirectToLoginPageSingleProvider() throws Exception {
|
||||
mockMvc.perform(get("http://localhost:8080/some/url"))
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(redirectedUrl("http://localhost:8080/saml2/authenticate/simplesamlphp"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAuthNRequest() throws Exception {
|
||||
mockMvc.perform(get("http://localhost:8080/saml2/authenticate/simplesamlphp"))
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(header().string("Location", startsWith("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php?SAMLRequest=")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRelayState() throws Exception {
|
||||
mockMvc.perform(
|
||||
get("http://localhost:8080/saml2/authenticate/simplesamlphp")
|
||||
.param("RelayState", "relay state value with spaces")
|
||||
)
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(header().string("Location", startsWith("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php?SAMLRequest=")))
|
||||
.andExpect(header().string("Location", containsString("RelayState=relay%20state%20value%20with%20spaces")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signedResponse() throws Exception {
|
||||
final String username = "testuser@spring.security.saml";
|
||||
Assertion assertion = buildAssertion(username);
|
||||
Response response = buildResponse(assertion);
|
||||
signXmlObject(response, getSigningCredential(idpCertificate, idpPrivateKey, UsageType.SIGNING));
|
||||
String xml = toXml(response);
|
||||
mockMvc.perform(post("http://localhost:8080/login/saml2/sso/simplesamlphp")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.param("SAMLResponse", OpenSamlActionTestingSupport.encode(xml.getBytes(UTF_8))))
|
||||
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername(username));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signedAssertion() throws Exception {
|
||||
final String username = "testuser@spring.security.saml";
|
||||
Assertion assertion = buildAssertion(username);
|
||||
Response response = buildResponse(assertion);
|
||||
signXmlObject(assertion, getSigningCredential(idpCertificate, idpPrivateKey, UsageType.SIGNING));
|
||||
String xml = toXml(response);
|
||||
final ResultActions actions = mockMvc
|
||||
.perform(post("http://localhost:8080/login/saml2/sso/simplesamlphp")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.param("SAMLResponse", OpenSamlActionTestingSupport.encode(xml.getBytes(UTF_8))))
|
||||
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername(username));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unsigned() throws Exception {
|
||||
Assertion assertion = buildAssertion("testuser@spring.security.saml");
|
||||
Response response = buildResponse(assertion);
|
||||
String xml = toXml(response);
|
||||
mockMvc.perform(post("http://localhost:8080/login/saml2/sso/simplesamlphp")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.param("SAMLResponse", OpenSamlActionTestingSupport.encode(xml.getBytes(UTF_8))))
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(redirectedUrl("/login?error"))
|
||||
.andExpect(unauthenticated());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signedResponseEncryptedAssertion() throws Exception {
|
||||
final String username = "testuser@spring.security.saml";
|
||||
Assertion assertion = buildAssertion(username);
|
||||
EncryptedAssertion encryptedAssertion =
|
||||
OpenSamlActionTestingSupport.encryptAssertion(assertion, decodeCertificate(spCertificate));
|
||||
Response response = buildResponse(encryptedAssertion);
|
||||
signXmlObject(assertion, getSigningCredential(idpCertificate, idpPrivateKey, UsageType.SIGNING));
|
||||
String xml = toXml(response);
|
||||
final ResultActions actions = mockMvc
|
||||
.perform(post("http://localhost:8080/login/saml2/sso/simplesamlphp")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.param("SAMLResponse", OpenSamlActionTestingSupport.encode(xml.getBytes(UTF_8))))
|
||||
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername(username));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unsignedResponseEncryptedAssertion() throws Exception {
|
||||
final String username = "testuser@spring.security.saml";
|
||||
Assertion assertion = buildAssertion(username);
|
||||
EncryptedAssertion encryptedAssertion =
|
||||
OpenSamlActionTestingSupport.encryptAssertion(assertion, decodeCertificate(spCertificate));
|
||||
Response response = buildResponse(encryptedAssertion);
|
||||
String xml = toXml(response);
|
||||
final ResultActions actions = mockMvc
|
||||
.perform(post("http://localhost:8080/login/saml2/sso/simplesamlphp")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.param("SAMLResponse", OpenSamlActionTestingSupport.encode(xml.getBytes(UTF_8))))
|
||||
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername(username));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void signedResponseEncryptedNameId() throws Exception {
|
||||
final String username = "testuser@spring.security.saml";
|
||||
Assertion assertion = buildAssertion(username);
|
||||
final EncryptedID nameId = encryptNameId(assertion.getSubject().getNameID(), decodeCertificate(spCertificate));
|
||||
assertion.getSubject().setEncryptedID(nameId);
|
||||
assertion.getSubject().setNameID(null);
|
||||
Response response = buildResponse(assertion);
|
||||
signXmlObject(assertion, getSigningCredential(idpCertificate, idpPrivateKey, UsageType.SIGNING));
|
||||
String xml = toXml(response);
|
||||
final ResultActions actions = mockMvc
|
||||
.perform(post("http://localhost:8080/login/saml2/sso/simplesamlphp")
|
||||
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
|
||||
.param("SAMLResponse", OpenSamlActionTestingSupport.encode(xml.getBytes(UTF_8))))
|
||||
.andExpect(status().is3xxRedirection()).andExpect(redirectedUrl("/"))
|
||||
.andExpect(authenticated().withUsername(username));
|
||||
}
|
||||
|
||||
private Response buildResponse(Assertion assertion) {
|
||||
Response response = buildResponse();
|
||||
response.getAssertions().add(assertion);
|
||||
return response;
|
||||
}
|
||||
|
||||
private Response buildResponse(EncryptedAssertion assertion) {
|
||||
Response response = buildResponse();
|
||||
response.getEncryptedAssertions().add(assertion);
|
||||
return response;
|
||||
}
|
||||
|
||||
private Response buildResponse() {
|
||||
Response response = OpenSamlActionTestingSupport.buildResponse();
|
||||
response.setID("_" + UUID.randomUUID().toString());
|
||||
response.setDestination("http://localhost:8080/login/saml2/sso/simplesamlphp");
|
||||
response.setIssuer(buildIssuer("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"));
|
||||
return response;
|
||||
}
|
||||
|
||||
private Assertion buildAssertion(String username) {
|
||||
Assertion assertion = OpenSamlActionTestingSupport.buildAssertion();
|
||||
assertion.setIssueInstant(DateTime.now());
|
||||
assertion.setIssuer(buildIssuer("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php"));
|
||||
assertion.setSubject(buildSubject(username));
|
||||
assertion.setConditions(buildConditions());
|
||||
|
||||
SubjectConfirmation subjectConfirmation = buildSubjectConfirmation();
|
||||
|
||||
// Default to bearer with basic valid confirmation data, but the test can change
|
||||
// as appropriate
|
||||
subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER);
|
||||
final SubjectConfirmationData confirmationData = buildSubjectConfirmationData(LOCAL_SP_ENTITY_ID);
|
||||
confirmationData.setRecipient("http://localhost:8080/login/saml2/sso/simplesamlphp");
|
||||
subjectConfirmation.setSubjectConfirmationData(confirmationData);
|
||||
assertion.getSubject().getSubjectConfirmations().add(subjectConfirmation);
|
||||
return assertion;
|
||||
}
|
||||
|
||||
protected Credential getSigningCredential(String certificate, String key, UsageType usageType)
|
||||
throws CertificateException, KeyException {
|
||||
PublicKey publicKey = decodeCertificate(certificate).getPublicKey();
|
||||
final PrivateKey privateKey = KeySupport.decodePrivateKey(key.getBytes(UTF_8), new char[0]);
|
||||
BasicCredential cred = CredentialSupport.getSimpleCredential(publicKey, privateKey);
|
||||
cred.setUsageType(usageType);
|
||||
cred.setEntityId("https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php");
|
||||
return cred;
|
||||
}
|
||||
|
||||
private void signXmlObject(SignableSAMLObject object, Credential credential)
|
||||
throws MarshallingException, SecurityException, SignatureException {
|
||||
SignatureSigningParameters parameters = new SignatureSigningParameters();
|
||||
parameters.setSigningCredential(credential);
|
||||
parameters.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256);
|
||||
parameters.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA256);
|
||||
parameters.setSignatureCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
|
||||
SignatureSupport.signObject(object, parameters);
|
||||
}
|
||||
|
||||
private String toXml(XMLObject object) throws MarshallingException {
|
||||
final MarshallerFactory marshallerFactory = XMLObjectProviderRegistrySupport.getMarshallerFactory();
|
||||
Element element = marshallerFactory.getMarshaller(object).marshall(object);
|
||||
return SerializeSupport.nodeToString(element);
|
||||
}
|
||||
|
||||
private X509Certificate decodeCertificate(String source) {
|
||||
try {
|
||||
final CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
return (X509Certificate) factory.generateCertificate(
|
||||
new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8))
|
||||
);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private String idpCertificate = "-----BEGIN CERTIFICATE-----\n"
|
||||
+ "MIIEEzCCAvugAwIBAgIJAIc1qzLrv+5nMA0GCSqGSIb3DQEBCwUAMIGfMQswCQYD\n"
|
||||
+ "VQQGEwJVUzELMAkGA1UECAwCQ08xFDASBgNVBAcMC0Nhc3RsZSBSb2NrMRwwGgYD\n"
|
||||
+ "VQQKDBNTYW1sIFRlc3RpbmcgU2VydmVyMQswCQYDVQQLDAJJVDEgMB4GA1UEAwwX\n"
|
||||
+ "c2ltcGxlc2FtbHBocC5jZmFwcHMuaW8xIDAeBgkqhkiG9w0BCQEWEWZoYW5pa0Bw\n"
|
||||
+ "aXZvdGFsLmlvMB4XDTE1MDIyMzIyNDUwM1oXDTI1MDIyMjIyNDUwM1owgZ8xCzAJ\n"
|
||||
+ "BgNVBAYTAlVTMQswCQYDVQQIDAJDTzEUMBIGA1UEBwwLQ2FzdGxlIFJvY2sxHDAa\n"
|
||||
+ "BgNVBAoME1NhbWwgVGVzdGluZyBTZXJ2ZXIxCzAJBgNVBAsMAklUMSAwHgYDVQQD\n"
|
||||
+ "DBdzaW1wbGVzYW1scGhwLmNmYXBwcy5pbzEgMB4GCSqGSIb3DQEJARYRZmhhbmlr\n"
|
||||
+ "QHBpdm90YWwuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4cn62\n"
|
||||
+ "E1xLqpN34PmbrKBbkOXFjzWgJ9b+pXuaRft6A339uuIQeoeH5qeSKRVTl32L0gdz\n"
|
||||
+ "2ZivLwZXW+cqvftVW1tvEHvzJFyxeTW3fCUeCQsebLnA2qRa07RkxTo6Nf244mWW\n"
|
||||
+ "RDodcoHEfDUSbxfTZ6IExSojSIU2RnD6WllYWFdD1GFpBJOmQB8rAc8wJIBdHFdQ\n"
|
||||
+ "nX8Ttl7hZ6rtgqEYMzYVMuJ2F2r1HSU1zSAvwpdYP6rRGFRJEfdA9mm3WKfNLSc5\n"
|
||||
+ "cljz0X/TXy0vVlAV95l9qcfFzPmrkNIst9FZSwpvB49LyAVke04FQPPwLgVH4gph\n"
|
||||
+ "iJH3jvZ7I+J5lS8VAgMBAAGjUDBOMB0GA1UdDgQWBBTTyP6Cc5HlBJ5+ucVCwGc5\n"
|
||||
+ "ogKNGzAfBgNVHSMEGDAWgBTTyP6Cc5HlBJ5+ucVCwGc5ogKNGzAMBgNVHRMEBTAD\n"
|
||||
+ "AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAvMS4EQeP/ipV4jOG5lO6/tYCb/iJeAduO\n"
|
||||
+ "nRhkJk0DbX329lDLZhTTL/x/w/9muCVcvLrzEp6PN+VWfw5E5FWtZN0yhGtP9R+v\n"
|
||||
+ "ZnrV+oc2zGD+no1/ySFOe3EiJCO5dehxKjYEmBRv5sU/LZFKZpozKN/BMEa6CqLu\n"
|
||||
+ "xbzb7ykxVr7EVFXwltPxzE9TmL9OACNNyF5eJHWMRMllarUvkcXlh4pux4ks9e6z\n"
|
||||
+ "V9DQBy2zds9f1I3qxg0eX6JnGrXi/ZiCT+lJgVe3ZFXiejiLAiKB04sXW3ti0LW3\n"
|
||||
+ "lx13Y1YlQ4/tlpgTgfIJxKV6nyPiLoK0nywbMd+vpAirDt2Oc+hk\n" + "-----END CERTIFICATE-----\n";
|
||||
|
||||
private String idpPrivateKey = "-----BEGIN PRIVATE KEY-----\n"
|
||||
+ "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC4cn62E1xLqpN3\n"
|
||||
+ "4PmbrKBbkOXFjzWgJ9b+pXuaRft6A339uuIQeoeH5qeSKRVTl32L0gdz2ZivLwZX\n"
|
||||
+ "W+cqvftVW1tvEHvzJFyxeTW3fCUeCQsebLnA2qRa07RkxTo6Nf244mWWRDodcoHE\n"
|
||||
+ "fDUSbxfTZ6IExSojSIU2RnD6WllYWFdD1GFpBJOmQB8rAc8wJIBdHFdQnX8Ttl7h\n"
|
||||
+ "Z6rtgqEYMzYVMuJ2F2r1HSU1zSAvwpdYP6rRGFRJEfdA9mm3WKfNLSc5cljz0X/T\n"
|
||||
+ "Xy0vVlAV95l9qcfFzPmrkNIst9FZSwpvB49LyAVke04FQPPwLgVH4gphiJH3jvZ7\n"
|
||||
+ "I+J5lS8VAgMBAAECggEBAKyxBlIS7mcp3chvq0RF7B3PHFJMMzkwE+t3pLJcs4cZ\n"
|
||||
+ "nezh/KbREfP70QjXzk/llnZCvxeIs5vRu24vbdBm79qLHqBuHp8XfHHtuo2AfoAQ\n"
|
||||
+ "l4h047Xc/+TKMivnPQ0jX9qqndKDLqZDf5wnbslDmlskvF0a/MjsLU0TxtOfo+dB\n"
|
||||
+ "t55FW11cGqxZwhS5Gnr+cbw3OkHz23b9gEOt9qfwPVepeysbmm9FjU+k4yVa7rAN\n"
|
||||
+ "xcbzVb6Y7GCITe2tgvvEHmjB9BLmWrH3mZ3Af17YU/iN6TrpPd6Sj3QoS+2wGtAe\n"
|
||||
+ "HbUs3CKJu7bIHcj4poal6Kh8519S+erJTtqQ8M0ZiEECgYEA43hLYAPaUueFkdfh\n"
|
||||
+ "9K/7ClH6436CUH3VdizwUXi26fdhhV/I/ot6zLfU2mgEHU22LBECWQGtAFm8kv0P\n"
|
||||
+ "zPn+qjaR3e62l5PIlSYbnkIidzoDZ2ztu4jF5LgStlTJQPteFEGgZVl5o9DaSZOq\n"
|
||||
+ "Yd7G3XqXuQ1VGMW58G5FYJPtA1cCgYEAz5TPUtK+R2KXHMjUwlGY9AefQYRYmyX2\n"
|
||||
+ "Tn/OFgKvY8lpAkMrhPKONq7SMYc8E9v9G7A0dIOXvW7QOYSapNhKU+np3lUafR5F\n"
|
||||
+ "4ZN0bxZ9qjHbn3AMYeraKjeutHvlLtbHdIc1j3sxe/EzltRsYmiqLdEBW0p6hwWg\n"
|
||||
+ "tyGhYWVyaXMCgYAfDOKtHpmEy5nOCLwNXKBWDk7DExfSyPqEgSnk1SeS1HP5ctPK\n"
|
||||
+ "+1st6sIhdiVpopwFc+TwJWxqKdW18tlfT5jVv1E2DEnccw3kXilS9xAhWkfwrEvf\n"
|
||||
+ "V5I74GydewFl32o+NZ8hdo9GL1I8zO1rIq/et8dSOWGuWf9BtKu/vTGTTQKBgFxU\n"
|
||||
+ "VjsCnbvmsEwPUAL2hE/WrBFaKocnxXx5AFNt8lEyHtDwy4Sg1nygGcIJ4sD6koQk\n"
|
||||
+ "RdClT3LkvR04TAiSY80bN/i6ZcPNGUwSaDGZEWAIOSWbkwZijZNFnSGOEgxZX/IG\n"
|
||||
+ "yd39766vREEMTwEeiMNEOZQ/dmxkJm4OOVe25cLdAoGACOtPnq1Fxay80UYBf4rQ\n"
|
||||
+ "+bJ9yX1ulB8WIree1hD7OHSB2lRHxrVYWrglrTvkh63Lgx+EcsTV788OsvAVfPPz\n"
|
||||
+ "BZrn8SdDlQqalMxUBYEFwnsYD3cQ8yOUnijFVC4xNcdDv8OIqVgSk4KKxU5AshaA\n" + "xk6Mox+u8Cc2eAK12H13i+8=\n"
|
||||
+ "-----END PRIVATE KEY-----\n";
|
||||
|
||||
private String spCertificate = "-----BEGIN CERTIFICATE-----\n" +
|
||||
"MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBhMC\n" +
|
||||
"VVMxEzARBgNVBAgMCldhc2hpbmd0b24xEjAQBgNVBAcMCVZhbmNvdXZlcjEdMBsG\n" +
|
||||
"A1UECgwUU3ByaW5nIFNlY3VyaXR5IFNBTUwxCzAJBgNVBAsMAnNwMSAwHgYDVQQD\n" +
|
||||
"DBdzcC5zcHJpbmcuc2VjdXJpdHkuc2FtbDAeFw0xODA1MTQxNDMwNDRaFw0yODA1\n" +
|
||||
"MTExNDMwNDRaMIGEMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjES\n" +
|
||||
"MBAGA1UEBwwJVmFuY291dmVyMR0wGwYDVQQKDBRTcHJpbmcgU2VjdXJpdHkgU0FN\n" +
|
||||
"TDELMAkGA1UECwwCc3AxIDAeBgNVBAMMF3NwLnNwcmluZy5zZWN1cml0eS5zYW1s\n" +
|
||||
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRu7/EI0BlNzMEBFVAcbx+lLos\n" +
|
||||
"vzIWU+01dGTY8gBdhMQNYKZ92lMceo2CuVJ66cUURPym3i7nGGzoSnAxAre+0YIM\n" +
|
||||
"+U0razrWtAUE735bkcqELZkOTZLelaoOztmWqRbe5OuEmpewH7cx+kNgcVjdctOG\n" +
|
||||
"y3Q6x+I4qakY/9qhBQIDAQABMA0GCSqGSIb3DQEBCwUAA4GBAAeViTvHOyQopWEi\n" +
|
||||
"XOfI2Z9eukwrSknDwq/zscR0YxwwqDBMt/QdAODfSwAfnciiYLkmEjlozWRtOeN+\n" +
|
||||
"qK7UFgP1bRl5qksrYX5S0z2iGJh0GvonLUt3e20Ssfl5tTEDDnAEUMLfBkyaxEHD\n" +
|
||||
"RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B\n" +
|
||||
"-----END CERTIFICATE-----";
|
||||
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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 boot.saml2.config;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.security.saml2.credentials.Saml2X509Credential;
|
||||
import org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository;
|
||||
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.servlet.filter.Saml2WebSsoAuthenticationFilter;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.util.Collections.emptyList;
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.DECRYPTION;
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION;
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.SIGNING;
|
||||
import static org.springframework.security.saml2.credentials.Saml2X509Credential.Saml2X509CredentialType.VERIFICATION;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "spring.security.saml2.login")
|
||||
@Import(X509CredentialsConverters.class)
|
||||
public class Saml2LoginBootConfiguration {
|
||||
|
||||
private List<SampleRelyingParty> relyingParties;
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public RelyingPartyRegistrationRepository relyingPartyRegistrationRepository() {
|
||||
return new InMemoryRelyingPartyRegistrationRepository(getRelyingParties(relyingParties));
|
||||
}
|
||||
|
||||
public void setRelyingParties(List<SampleRelyingParty> providers) {
|
||||
this.relyingParties = providers;
|
||||
}
|
||||
|
||||
private List<RelyingPartyRegistration> getRelyingParties(List<SampleRelyingParty> sampleRelyingParties) {
|
||||
String acsUrlTemplate = "{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI;
|
||||
return sampleRelyingParties.stream()
|
||||
.map(
|
||||
p -> StringUtils.hasText(p.getLocalSpEntityIdTemplate()) ?
|
||||
RelyingPartyRegistration.withRegistrationId(p.getRegistrationId())
|
||||
.assertionConsumerServiceUrlTemplate(acsUrlTemplate)
|
||||
.remoteIdpEntityId(p.getEntityId())
|
||||
.idpWebSsoUrl(p.getWebSsoUrl())
|
||||
.credentials(c -> c.addAll(p.getProviderCredentials()))
|
||||
.localEntityIdTemplate(p.getLocalSpEntityIdTemplate())
|
||||
.build() :
|
||||
RelyingPartyRegistration.withRegistrationId(p.getRegistrationId())
|
||||
.assertionConsumerServiceUrlTemplate(acsUrlTemplate)
|
||||
.remoteIdpEntityId(p.getEntityId())
|
||||
.idpWebSsoUrl(p.getWebSsoUrl())
|
||||
.credentials(c -> c.addAll(p.getProviderCredentials()))
|
||||
.build()
|
||||
)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static class SampleRelyingParty {
|
||||
|
||||
private String entityId;
|
||||
private List<Saml2X509Credential> signingCredentials = emptyList();
|
||||
private List<X509Certificate> verificationCredentials = emptyList();
|
||||
private String registrationId;
|
||||
private String webSsoUrl;
|
||||
private String localSpEntityIdTemplate;
|
||||
|
||||
public String getEntityId() {
|
||||
return entityId;
|
||||
}
|
||||
|
||||
public String getLocalSpEntityIdTemplate() {
|
||||
return localSpEntityIdTemplate;
|
||||
}
|
||||
|
||||
public void setEntityId(String entityId) {
|
||||
this.entityId = entityId;
|
||||
}
|
||||
|
||||
public List<Saml2X509Credential> getSigningCredentials() {
|
||||
return signingCredentials;
|
||||
}
|
||||
|
||||
public void setSigningCredentials(List<X509KeyCertificatePair> credentials) {
|
||||
this.signingCredentials = credentials
|
||||
.stream()
|
||||
.map(c ->
|
||||
new Saml2X509Credential(
|
||||
c.getPrivateKey(),
|
||||
c.getCertificate(),
|
||||
SIGNING,
|
||||
DECRYPTION
|
||||
)
|
||||
)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public void setVerificationCredentials(List<X509Certificate> credentials) {
|
||||
this.verificationCredentials = new LinkedList<>(credentials);
|
||||
}
|
||||
|
||||
public List<X509Certificate> getVerificationCredentials() {
|
||||
return verificationCredentials;
|
||||
}
|
||||
|
||||
public List<Saml2X509Credential> getProviderCredentials() {
|
||||
LinkedList<Saml2X509Credential> result = new LinkedList<>(getSigningCredentials());
|
||||
for (X509Certificate c : getVerificationCredentials()) {
|
||||
result.add(new Saml2X509Credential(c, ENCRYPTION, VERIFICATION));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getRegistrationId() {
|
||||
return registrationId;
|
||||
}
|
||||
|
||||
public SampleRelyingParty setRegistrationId(String registrationId) {
|
||||
this.registrationId = registrationId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getWebSsoUrl() {
|
||||
return webSsoUrl;
|
||||
}
|
||||
|
||||
public SampleRelyingParty setWebSsoUrl(String webSsoUrl) {
|
||||
this.webSsoUrl = webSsoUrl;
|
||||
return this;
|
||||
}
|
||||
|
||||
public void setLocalSpEntityIdTemplate(String localSpEntityIdTemplate) {
|
||||
this.localSpEntityIdTemplate = localSpEntityIdTemplate;
|
||||
}
|
||||
}
|
||||
|
||||
public static class X509KeyCertificatePair {
|
||||
|
||||
private RSAPrivateKey privateKey;
|
||||
private X509Certificate certificate;
|
||||
|
||||
public RSAPrivateKey getPrivateKey() {
|
||||
return this.privateKey;
|
||||
}
|
||||
|
||||
public void setPrivateKey(RSAPrivateKey privateKey) {
|
||||
this.privateKey = privateKey;
|
||||
}
|
||||
|
||||
public X509Certificate getCertificate() {
|
||||
return certificate;
|
||||
}
|
||||
|
||||
public void setCertificate(X509Certificate certificate) {
|
||||
this.certificate = certificate;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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 boot.saml2.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.security.converter.RsaKeyConverters;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
|
||||
import static java.nio.charset.StandardCharsets.UTF_8;
|
||||
|
||||
@Configuration
|
||||
public class X509CredentialsConverters {
|
||||
|
||||
@Component
|
||||
@ConfigurationPropertiesBinding
|
||||
public static class X509CertificateConverter implements Converter<String, X509Certificate> {
|
||||
@Override
|
||||
public X509Certificate convert (String source){
|
||||
try {
|
||||
final CertificateFactory factory = CertificateFactory.getInstance("X.509");
|
||||
return (X509Certificate) factory.generateCertificate(
|
||||
new ByteArrayInputStream(source.getBytes(UTF_8))
|
||||
);
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new IllegalArgumentException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Component
|
||||
@ConfigurationPropertiesBinding
|
||||
public static class RSAPrivateKeyConverter implements Converter<String, RSAPrivateKey> {
|
||||
@Override
|
||||
public RSAPrivateKey convert (String source){
|
||||
return RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(source.getBytes(UTF_8)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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 sample;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import sample.Saml2LoginApplication;
|
||||
|
||||
@Controller
|
||||
public class IndexController {
|
||||
|
||||
private static final Log logger = LogFactory.getLog(Saml2LoginApplication.class);
|
||||
|
||||
@GetMapping("/")
|
||||
public String index() {
|
||||
return "index";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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 sample;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import boot.saml2.config.Saml2LoginBootConfiguration;
|
||||
|
||||
@SpringBootApplication
|
||||
@Import(Saml2LoginBootConfiguration.class)
|
||||
public class Saml2LoginApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Saml2LoginApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright 2002-2019 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 sample;
|
||||
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
//@formatter:off
|
||||
http
|
||||
.authorizeRequests()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.saml2Login()
|
||||
;
|
||||
//@formatter:on
|
||||
}
|
||||
|
||||
}
|
||||
69
samples/boot/saml2login/src/main/resources/application.yml
Normal file
69
samples/boot/saml2login/src/main/resources/application.yml
Normal file
@@ -0,0 +1,69 @@
|
||||
spring:
|
||||
security:
|
||||
saml2:
|
||||
login:
|
||||
relying-parties:
|
||||
- entity-id: https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/metadata.php
|
||||
registration-id: simplesamlphp
|
||||
web-sso-url: https://simplesaml-for-spring-saml.cfapps.io/saml2/idp/SSOService.php
|
||||
signing-credentials:
|
||||
- private-key: |
|
||||
-----BEGIN PRIVATE KEY-----
|
||||
MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANG7v8QjQGU3MwQE
|
||||
VUBxvH6Uuiy/MhZT7TV0ZNjyAF2ExA1gpn3aUxx6jYK5UnrpxRRE/KbeLucYbOhK
|
||||
cDECt77Rggz5TStrOta0BQTvfluRyoQtmQ5Nkt6Vqg7O2ZapFt7k64Sal7AftzH6
|
||||
Q2BxWN1y04bLdDrH4jipqRj/2qEFAgMBAAECgYEAj4ExY1jjdN3iEDuOwXuRB+Nn
|
||||
x7pC4TgntE2huzdKvLJdGvIouTArce8A6JM5NlTBvm69mMepvAHgcsiMH1zGr5J5
|
||||
wJz23mGOyhM1veON41/DJTVG+cxq4soUZhdYy3bpOuXGMAaJ8QLMbQQoivllNihd
|
||||
vwH0rNSK8LTYWWPZYIECQQDxct+TFX1VsQ1eo41K0T4fu2rWUaxlvjUGhK6HxTmY
|
||||
8OMJptunGRJL1CUjIb45Uz7SP8TPz5FwhXWsLfS182kRAkEA3l+Qd9C9gdpUh1uX
|
||||
oPSNIxn5hFUrSTW1EwP9QH9vhwb5Vr8Jrd5ei678WYDLjUcx648RjkjhU9jSMzIx
|
||||
EGvYtQJBAMm/i9NR7IVyyNIgZUpz5q4LI21rl1r4gUQuD8vA36zM81i4ROeuCly0
|
||||
KkfdxR4PUfnKcQCX11YnHjk9uTFj75ECQEFY/gBnxDjzqyF35hAzrYIiMPQVfznt
|
||||
YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr
|
||||
9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM
|
||||
INrtuLp4YHbgk1mi
|
||||
-----END PRIVATE KEY-----
|
||||
certificate: |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBhMC
|
||||
VVMxEzARBgNVBAgMCldhc2hpbmd0b24xEjAQBgNVBAcMCVZhbmNvdXZlcjEdMBsG
|
||||
A1UECgwUU3ByaW5nIFNlY3VyaXR5IFNBTUwxCzAJBgNVBAsMAnNwMSAwHgYDVQQD
|
||||
DBdzcC5zcHJpbmcuc2VjdXJpdHkuc2FtbDAeFw0xODA1MTQxNDMwNDRaFw0yODA1
|
||||
MTExNDMwNDRaMIGEMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjES
|
||||
MBAGA1UEBwwJVmFuY291dmVyMR0wGwYDVQQKDBRTcHJpbmcgU2VjdXJpdHkgU0FN
|
||||
TDELMAkGA1UECwwCc3AxIDAeBgNVBAMMF3NwLnNwcmluZy5zZWN1cml0eS5zYW1s
|
||||
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRu7/EI0BlNzMEBFVAcbx+lLos
|
||||
vzIWU+01dGTY8gBdhMQNYKZ92lMceo2CuVJ66cUURPym3i7nGGzoSnAxAre+0YIM
|
||||
+U0razrWtAUE735bkcqELZkOTZLelaoOztmWqRbe5OuEmpewH7cx+kNgcVjdctOG
|
||||
y3Q6x+I4qakY/9qhBQIDAQABMA0GCSqGSIb3DQEBCwUAA4GBAAeViTvHOyQopWEi
|
||||
XOfI2Z9eukwrSknDwq/zscR0YxwwqDBMt/QdAODfSwAfnciiYLkmEjlozWRtOeN+
|
||||
qK7UFgP1bRl5qksrYX5S0z2iGJh0GvonLUt3e20Ssfl5tTEDDnAEUMLfBkyaxEHD
|
||||
RZ/nbTJ7VTeZOSyRoVn5XHhpuJ0B
|
||||
-----END CERTIFICATE-----
|
||||
verification-credentials:
|
||||
- |
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIEEzCCAvugAwIBAgIJAIc1qzLrv+5nMA0GCSqGSIb3DQEBCwUAMIGfMQswCQYD
|
||||
VQQGEwJVUzELMAkGA1UECAwCQ08xFDASBgNVBAcMC0Nhc3RsZSBSb2NrMRwwGgYD
|
||||
VQQKDBNTYW1sIFRlc3RpbmcgU2VydmVyMQswCQYDVQQLDAJJVDEgMB4GA1UEAwwX
|
||||
c2ltcGxlc2FtbHBocC5jZmFwcHMuaW8xIDAeBgkqhkiG9w0BCQEWEWZoYW5pa0Bw
|
||||
aXZvdGFsLmlvMB4XDTE1MDIyMzIyNDUwM1oXDTI1MDIyMjIyNDUwM1owgZ8xCzAJ
|
||||
BgNVBAYTAlVTMQswCQYDVQQIDAJDTzEUMBIGA1UEBwwLQ2FzdGxlIFJvY2sxHDAa
|
||||
BgNVBAoME1NhbWwgVGVzdGluZyBTZXJ2ZXIxCzAJBgNVBAsMAklUMSAwHgYDVQQD
|
||||
DBdzaW1wbGVzYW1scGhwLmNmYXBwcy5pbzEgMB4GCSqGSIb3DQEJARYRZmhhbmlr
|
||||
QHBpdm90YWwuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4cn62
|
||||
E1xLqpN34PmbrKBbkOXFjzWgJ9b+pXuaRft6A339uuIQeoeH5qeSKRVTl32L0gdz
|
||||
2ZivLwZXW+cqvftVW1tvEHvzJFyxeTW3fCUeCQsebLnA2qRa07RkxTo6Nf244mWW
|
||||
RDodcoHEfDUSbxfTZ6IExSojSIU2RnD6WllYWFdD1GFpBJOmQB8rAc8wJIBdHFdQ
|
||||
nX8Ttl7hZ6rtgqEYMzYVMuJ2F2r1HSU1zSAvwpdYP6rRGFRJEfdA9mm3WKfNLSc5
|
||||
cljz0X/TXy0vVlAV95l9qcfFzPmrkNIst9FZSwpvB49LyAVke04FQPPwLgVH4gph
|
||||
iJH3jvZ7I+J5lS8VAgMBAAGjUDBOMB0GA1UdDgQWBBTTyP6Cc5HlBJ5+ucVCwGc5
|
||||
ogKNGzAfBgNVHSMEGDAWgBTTyP6Cc5HlBJ5+ucVCwGc5ogKNGzAMBgNVHRMEBTAD
|
||||
AQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAvMS4EQeP/ipV4jOG5lO6/tYCb/iJeAduO
|
||||
nRhkJk0DbX329lDLZhTTL/x/w/9muCVcvLrzEp6PN+VWfw5E5FWtZN0yhGtP9R+v
|
||||
ZnrV+oc2zGD+no1/ySFOe3EiJCO5dehxKjYEmBRv5sU/LZFKZpozKN/BMEa6CqLu
|
||||
xbzb7ykxVr7EVFXwltPxzE9TmL9OACNNyF5eJHWMRMllarUvkcXlh4pux4ks9e6z
|
||||
V9DQBy2zds9f1I3qxg0eX6JnGrXi/ZiCT+lJgVe3ZFXiejiLAiKB04sXW3ti0LW3
|
||||
lx13Y1YlQ4/tlpgTgfIJxKV6nyPiLoK0nywbMd+vpAirDt2Oc+hk
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,37 @@
|
||||
<!--
|
||||
~ Copyright 2002-2019 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.
|
||||
-->
|
||||
|
||||
<!doctype html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
|
||||
<head>
|
||||
<title>Spring Security - SAML 2 Log In</title>
|
||||
<meta charset="utf-8" />
|
||||
</head>
|
||||
<body>
|
||||
<h1>Success</h1>
|
||||
<div>You are authenticated as <span sec:authentication="name"></span></div>
|
||||
<ul>
|
||||
<li>
|
||||
<a th:href="@{/logout}">Log Out</a>
|
||||
</li>
|
||||
<li>
|
||||
<a href="https://simplesaml-for-spring-saml.cfapps.io/module.php/core/authenticate.php?as=example-userpass&logout">
|
||||
Log out of SimpleSAMLPhp
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user