repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2Utils.java
/* * 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.core; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; 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; public final class Saml2Utils { private Saml2Utils() { } public static String samlEncode(byte[] b) { return Base64.getEncoder().encodeToString(b); } public static byte[] samlDecode(String s) { return Base64.getMimeDecoder().decode(s); } public static byte[] samlDeflate(String s) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(out, new Deflater(Deflater.DEFLATED, true)); deflaterOutputStream.write(s.getBytes(StandardCharsets.UTF_8)); deflaterOutputStream.finish(); return out.toByteArray(); } catch (IOException ex) { throw new Saml2Exception("Unable to deflate string", ex); } } public static 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 (IOException ex) { throw new Saml2Exception("Unable to inflate string", ex); } } }
2,168
29.549296
97
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/Saml2X509CredentialTests.java
/* * 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.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.converter.RsaKeyConverters; import org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; public class Saml2X509CredentialTests { private PrivateKey key; private X509Certificate certificate; @BeforeEach public void setup() throws Exception { String keyData = "-----BEGIN PRIVATE KEY-----\n" + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANG7v8QjQGU3MwQE\n" + "VUBxvH6Uuiy/MhZT7TV0ZNjyAF2ExA1gpn3aUxx6jYK5UnrpxRRE/KbeLucYbOhK\n" + "cDECt77Rggz5TStrOta0BQTvfluRyoQtmQ5Nkt6Vqg7O2ZapFt7k64Sal7AftzH6\n" + "Q2BxWN1y04bLdDrH4jipqRj/2qEFAgMBAAECgYEAj4ExY1jjdN3iEDuOwXuRB+Nn\n" + "x7pC4TgntE2huzdKvLJdGvIouTArce8A6JM5NlTBvm69mMepvAHgcsiMH1zGr5J5\n" + "wJz23mGOyhM1veON41/DJTVG+cxq4soUZhdYy3bpOuXGMAaJ8QLMbQQoivllNihd\n" + "vwH0rNSK8LTYWWPZYIECQQDxct+TFX1VsQ1eo41K0T4fu2rWUaxlvjUGhK6HxTmY\n" + "8OMJptunGRJL1CUjIb45Uz7SP8TPz5FwhXWsLfS182kRAkEA3l+Qd9C9gdpUh1uX\n" + "oPSNIxn5hFUrSTW1EwP9QH9vhwb5Vr8Jrd5ei678WYDLjUcx648RjkjhU9jSMzIx\n" + "EGvYtQJBAMm/i9NR7IVyyNIgZUpz5q4LI21rl1r4gUQuD8vA36zM81i4ROeuCly0\n" + "KkfdxR4PUfnKcQCX11YnHjk9uTFj75ECQEFY/gBnxDjzqyF35hAzrYIiMPQVfznt\n" + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"; this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(StandardCharsets.UTF_8))); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); String certificateData = "-----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-----"; this.certificate = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(StandardCharsets.UTF_8))); } @Test public void constructorWhenRelyingPartyWithCredentialsThenItSucceeds() { new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.SIGNING); new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.SIGNING, Saml2X509CredentialType.DECRYPTION); new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.DECRYPTION); Saml2X509Credential.signing(this.key, this.certificate); Saml2X509Credential.decryption(this.key, this.certificate); } @Test public void constructorWhenAssertingPartyWithCredentialsThenItSucceeds() { new Saml2X509Credential(this.certificate, Saml2X509CredentialType.VERIFICATION); new Saml2X509Credential(this.certificate, Saml2X509CredentialType.VERIFICATION, Saml2X509CredentialType.ENCRYPTION); new Saml2X509Credential(this.certificate, Saml2X509CredentialType.ENCRYPTION); Saml2X509Credential.verification(this.certificate); Saml2X509Credential.encryption(this.certificate); } @Test public void constructorWhenRelyingPartyWithoutCredentialsThenItFails() { assertThatIllegalArgumentException().isThrownBy( () -> new Saml2X509Credential(null, (X509Certificate) null, Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithoutPrivateKeyThenItFails() { assertThatIllegalArgumentException() .isThrownBy(() -> new Saml2X509Credential(null, this.certificate, Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithoutCertificateThenItFails() { assertThatIllegalArgumentException() .isThrownBy(() -> new Saml2X509Credential(this.key, null, Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenAssertingPartyWithoutCertificateThenItFails() { assertThatIllegalArgumentException() .isThrownBy(() -> new Saml2X509Credential(null, Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithEncryptionUsageThenItFails() { assertThatIllegalStateException().isThrownBy( () -> new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.ENCRYPTION)); } @Test public void constructorWhenRelyingPartyWithVerificationUsageThenItFails() { assertThatIllegalStateException().isThrownBy( () -> new Saml2X509Credential(this.key, this.certificate, Saml2X509CredentialType.VERIFICATION)); } @Test public void constructorWhenAssertingPartyWithSigningUsageThenItFails() { assertThatIllegalStateException() .isThrownBy(() -> new Saml2X509Credential(this.certificate, Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenAssertingPartyWithDecryptionUsageThenItFails() { assertThatIllegalStateException() .isThrownBy(() -> new Saml2X509Credential(this.certificate, Saml2X509CredentialType.DECRYPTION)); } @Test public void factoryWhenRelyingPartyForSigningWithoutCredentialsThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.signing(null, null)); } @Test public void factoryWhenRelyingPartyForSigningWithoutPrivateKeyThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.signing(null, this.certificate)); } @Test public void factoryWhenRelyingPartyForSigningWithoutCertificateThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.signing(this.key, null)); } @Test public void factoryWhenRelyingPartyForDecryptionWithoutCredentialsThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.decryption(null, null)); } @Test public void factoryWhenRelyingPartyForDecryptionWithoutPrivateKeyThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.decryption(null, this.certificate)); } @Test public void factoryWhenRelyingPartyForDecryptionWithoutCertificateThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.decryption(this.key, null)); } @Test public void factoryWhenAssertingPartyForVerificationWithoutCertificateThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.verification(null)); } @Test public void factoryWhenAssertingPartyForEncryptionWithoutCertificateThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> Saml2X509Credential.encryption(null)); } }
8,342
43.614973
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/core/TestSaml2X509Credentials.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.core; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.KeyException; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import org.opensaml.security.crypto.KeySupport; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType; public final class TestSaml2X509Credentials { private TestSaml2X509Credentials() { } public static Saml2X509Credential assertingPartySigningCredential() { return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential assertingPartyEncryptingCredential() { return new Saml2X509Credential(spCertificate(), Saml2X509CredentialType.ENCRYPTION); } public static Saml2X509Credential assertingPartyPrivateCredential() { return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509CredentialType.SIGNING, Saml2X509CredentialType.DECRYPTION); } public static Saml2X509Credential relyingPartyVerifyingCredential() { return new Saml2X509Credential(idpCertificate(), Saml2X509CredentialType.VERIFICATION); } public static Saml2X509Credential relyingPartyEncryptingCredential() { return new Saml2X509Credential(idpCertificate(), Saml2X509CredentialType.ENCRYPTION); } public static Saml2X509Credential relyingPartySigningCredential() { return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential relyingPartyDecryptingCredential() { return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509CredentialType.DECRYPTION); } public static Saml2X509Credential altPublicCredential() { return new Saml2X509Credential(altCertificate(), Saml2X509CredentialType.VERIFICATION, Saml2X509CredentialType.ENCRYPTION); } public static Saml2X509Credential altPrivateCredential() { return new Saml2X509Credential(altPrivateKey(), altCertificate(), Saml2X509CredentialType.SIGNING, Saml2X509CredentialType.DECRYPTION); } private static X509Certificate certificate(String cert) { ByteArrayInputStream certBytes = new ByteArrayInputStream(cert.getBytes()); try { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certBytes); } catch (CertificateException ex) { throw new Saml2Exception(ex); } } private static PrivateKey privateKey(String key) { try { return KeySupport.decodePrivateKey(key.getBytes(StandardCharsets.UTF_8), new char[0]); } catch (KeyException ex) { throw new Saml2Exception(ex); } } private static X509Certificate idpCertificate() { return certificate( "-----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 static PrivateKey idpPrivateKey() { return privateKey( "-----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 static X509Certificate spCertificate() { return certificate( "-----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-----"); } private static PrivateKey spPrivateKey() { return privateKey( "-----BEGIN PRIVATE KEY-----\n" + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANG7v8QjQGU3MwQE\n" + "VUBxvH6Uuiy/MhZT7TV0ZNjyAF2ExA1gpn3aUxx6jYK5UnrpxRRE/KbeLucYbOhK\n" + "cDECt77Rggz5TStrOta0BQTvfluRyoQtmQ5Nkt6Vqg7O2ZapFt7k64Sal7AftzH6\n" + "Q2BxWN1y04bLdDrH4jipqRj/2qEFAgMBAAECgYEAj4ExY1jjdN3iEDuOwXuRB+Nn\n" + "x7pC4TgntE2huzdKvLJdGvIouTArce8A6JM5NlTBvm69mMepvAHgcsiMH1zGr5J5\n" + "wJz23mGOyhM1veON41/DJTVG+cxq4soUZhdYy3bpOuXGMAaJ8QLMbQQoivllNihd\n" + "vwH0rNSK8LTYWWPZYIECQQDxct+TFX1VsQ1eo41K0T4fu2rWUaxlvjUGhK6HxTmY\n" + "8OMJptunGRJL1CUjIb45Uz7SP8TPz5FwhXWsLfS182kRAkEA3l+Qd9C9gdpUh1uX\n" + "oPSNIxn5hFUrSTW1EwP9QH9vhwb5Vr8Jrd5ei678WYDLjUcx648RjkjhU9jSMzIx\n" + "EGvYtQJBAMm/i9NR7IVyyNIgZUpz5q4LI21rl1r4gUQuD8vA36zM81i4ROeuCly0\n" + "KkfdxR4PUfnKcQCX11YnHjk9uTFj75ECQEFY/gBnxDjzqyF35hAzrYIiMPQVfznt\n" + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"); } private static X509Certificate altCertificate() { return certificate( "-----BEGIN CERTIFICATE-----\n" + "MIICkDCCAfkCFEstVfmWSFQp/j88GaMUwqVK72adMA0GCSqGSIb3DQEBCwUAMIGG\n" + "MQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjESMBAGA1UEBwwJVmFu\n" + "Y291dmVyMR0wGwYDVQQKDBRTcHJpbmcgU2VjdXJpdHkgU0FNTDEMMAoGA1UECwwD\n" + "YWx0MSEwHwYDVQQDDBhhbHQuc3ByaW5nLnNlY3VyaXR5LnNhbWwwHhcNMjIwMjEw\n" + "MTY1ODA4WhcNMzIwMjEwMTY1ODA4WjCBhjELMAkGA1UEBhMCVVMxEzARBgNVBAgM\n" + "Cldhc2hpbmd0b24xEjAQBgNVBAcMCVZhbmNvdXZlcjEdMBsGA1UECgwUU3ByaW5n\n" + "IFNlY3VyaXR5IFNBTUwxDDAKBgNVBAsMA2FsdDEhMB8GA1UEAwwYYWx0LnNwcmlu\n" + "Zy5zZWN1cml0eS5zYW1sMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC9ZGWj\n" + "TPDsymQCJL044py4xLsBI/S9RvzNeR9oD/tHyoxCE+YZzjf0PyBtwqKzkKWqCPf4\n" + "XGUYHfEpkM5kJYwCW8TsOx5fnwLIQweiPqjYrBr/O0IjHMqYG9HlR/ros7iBt4ab\n" + "EGUu/B9yYg1YRYPxKQ6TNP3AD+9tBT8TsFFyjwIDAQABMA0GCSqGSIb3DQEBCwUA\n" + "A4GBAKJf2VHLjkCHRxlbWn63jGiquq3ENYgd1JS0DZ3ggFmuc6zQiqxzRGtArIDZ\n" + "0jH5nrG0jcvO0fqDqBQh0iT8thfUnkViAQvACZ9a+0x0NzUicJ+Ra51c8Z2enqbg\n" + "pXy+ga67HcAXrDekm1MCGCgiEb/Cgl41lsideqhC8Efl7PRN\n" + "-----END CERTIFICATE-----"); } private static PrivateKey altPrivateKey() { return privateKey( "-----BEGIN PRIVATE KEY-----\n" + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAL1kZaNM8OzKZAIk\n" + "vTjinLjEuwEj9L1G/M15H2gP+0fKjEIT5hnON/Q/IG3CorOQpaoI9/hcZRgd8SmQ\n" + "zmQljAJbxOw7Hl+fAshDB6I+qNisGv87QiMcypgb0eVH+uizuIG3hpsQZS78H3Ji\n" + "DVhFg/EpDpM0/cAP720FPxOwUXKPAgMBAAECgYEApYKslAZ0cer5dSoYNzNLFOnQ\n" + "J1H92r/Dw+k6+h0lUvr+keyD5T9jhM76DxHOUDBzpmIKGoDcVDQugk2rILfzXsQA\n" + "JtwvDRJk32Z02Vt0jb7t/WUOOQhjKCjQuv9/tOx90GCl0VxYG69UOjaMRWrlg/i9\n" + "6/zcTRIahIn5XxF0psECQQD7ivJCpDbOLJGsc8gNJR4cvjZ1q0mHIOrbKqJC0y1n\n" + "5DrzGEflPeyCUwnOKNp9HJQP8gmZzXfj0JM9KsjpiUChAkEAwL+FmhDoTiqStIrH\n" + "h9Kdnsev//imMmRHxjwDhntYvqavUsISRmY3imd8inoYq5dzWQMzBtoTyMRmqeLT\n" + "DHV1LwJAW4xaV37Eo4z9B7Kr4Hzd1MA1ueW5QQDt+Q4vN/r7z4/1FHyFzh0Xcucd\n" + "7nZX7qj0CkmgzOVG+Rb0P5LOxJA7gQJBAK1KQ2qNct375qPM9bEGSVGchH6k5X7+\n" + "q4ztHdpFgTb/EzdbZiTG935GpjC1rwJuinTnrHOnkwv4j7iDRm24GF8CQQDqPvrQ\n" + "GcItR6UUy0q/B8UxLzlE6t+HiznfiJKfyGgCHU56Y4/ZhzSQz2MZHz9SK4DsUL9s\n" + "bOYrWq8VY2fyjV1t\n" + "-----END PRIVATE KEY-----"); } }
12,060
52.84375
106
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/Saml2X509CredentialTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.credentials; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.security.converter.RsaKeyConverters; import org.springframework.security.saml2.core.Saml2X509Credential; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatIllegalStateException; public class Saml2X509CredentialTests { private Saml2X509Credential credential; private PrivateKey key; private X509Certificate certificate; @BeforeEach public void setup() throws Exception { String keyData = "-----BEGIN PRIVATE KEY-----\n" + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANG7v8QjQGU3MwQE\n" + "VUBxvH6Uuiy/MhZT7TV0ZNjyAF2ExA1gpn3aUxx6jYK5UnrpxRRE/KbeLucYbOhK\n" + "cDECt77Rggz5TStrOta0BQTvfluRyoQtmQ5Nkt6Vqg7O2ZapFt7k64Sal7AftzH6\n" + "Q2BxWN1y04bLdDrH4jipqRj/2qEFAgMBAAECgYEAj4ExY1jjdN3iEDuOwXuRB+Nn\n" + "x7pC4TgntE2huzdKvLJdGvIouTArce8A6JM5NlTBvm69mMepvAHgcsiMH1zGr5J5\n" + "wJz23mGOyhM1veON41/DJTVG+cxq4soUZhdYy3bpOuXGMAaJ8QLMbQQoivllNihd\n" + "vwH0rNSK8LTYWWPZYIECQQDxct+TFX1VsQ1eo41K0T4fu2rWUaxlvjUGhK6HxTmY\n" + "8OMJptunGRJL1CUjIb45Uz7SP8TPz5FwhXWsLfS182kRAkEA3l+Qd9C9gdpUh1uX\n" + "oPSNIxn5hFUrSTW1EwP9QH9vhwb5Vr8Jrd5ei678WYDLjUcx648RjkjhU9jSMzIx\n" + "EGvYtQJBAMm/i9NR7IVyyNIgZUpz5q4LI21rl1r4gUQuD8vA36zM81i4ROeuCly0\n" + "KkfdxR4PUfnKcQCX11YnHjk9uTFj75ECQEFY/gBnxDjzqyF35hAzrYIiMPQVfznt\n" + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"; this.key = RsaKeyConverters.pkcs8().convert(new ByteArrayInputStream(keyData.getBytes(StandardCharsets.UTF_8))); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); String certificateData = "-----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-----"; this.certificate = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(certificateData.getBytes(StandardCharsets.UTF_8))); } @Test public void constructorWhenRelyingPartyWithCredentialsThenItSucceeds() { new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING); new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } @Test public void constructorWhenAssertingPartyWithCredentialsThenItSucceeds() { new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); } @Test public void constructorWhenRelyingPartyWithoutCredentialsThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> new Saml2X509Credential(null, (X509Certificate) null, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithoutPrivateKeyThenItFails() { assertThatIllegalArgumentException().isThrownBy(() -> new Saml2X509Credential(null, this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithoutCertificateThenItFails() { assertThatIllegalArgumentException().isThrownBy( () -> new Saml2X509Credential(this.key, null, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenAssertingPartyWithoutCertificateThenItFails() { assertThatIllegalArgumentException() .isThrownBy(() -> new Saml2X509Credential(null, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenRelyingPartyWithEncryptionUsageThenItFails() { assertThatIllegalStateException().isThrownBy(() -> new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION)); } @Test public void constructorWhenRelyingPartyWithVerificationUsageThenItFails() { assertThatIllegalStateException().isThrownBy(() -> new Saml2X509Credential(this.key, this.certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION)); } @Test public void constructorWhenAssertingPartyWithSigningUsageThenItFails() { assertThatIllegalStateException().isThrownBy( () -> new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING)); } @Test public void constructorWhenAssertingPartyWithDecryptionUsageThenItFails() { assertThatIllegalStateException().isThrownBy(() -> new Saml2X509Credential(this.certificate, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION)); } }
6,887
46.503448
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/credentials/TestSaml2X509Credentials.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.credentials; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.security.KeyException; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import org.opensaml.security.crypto.KeySupport; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential; public final class TestSaml2X509Credentials { private TestSaml2X509Credentials() { } public static Saml2X509Credential assertingPartySigningCredential() { return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509Credential.Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential assertingPartyEncryptingCredential() { return new Saml2X509Credential(spCertificate(), Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); } public static Saml2X509Credential assertingPartyPrivateCredential() { return new Saml2X509Credential(idpPrivateKey(), idpCertificate(), Saml2X509Credential.Saml2X509CredentialType.SIGNING, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } public static Saml2X509Credential relyingPartyVerifyingCredential() { return new Saml2X509Credential(idpCertificate(), Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); } public static Saml2X509Credential relyingPartySigningCredential() { return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509Credential.Saml2X509CredentialType.SIGNING); } public static Saml2X509Credential relyingPartyDecryptingCredential() { return new Saml2X509Credential(spPrivateKey(), spCertificate(), Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } private static X509Certificate certificate(String cert) { ByteArrayInputStream certBytes = new ByteArrayInputStream(cert.getBytes()); try { return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certBytes); } catch (CertificateException ex) { throw new Saml2Exception(ex); } } private static PrivateKey privateKey(String key) { try { return KeySupport.decodePrivateKey(key.getBytes(StandardCharsets.UTF_8), new char[0]); } catch (KeyException ex) { throw new Saml2Exception(ex); } } private static X509Certificate idpCertificate() { return certificate( "-----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 static PrivateKey idpPrivateKey() { return privateKey( "-----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 static X509Certificate spCertificate() { return certificate( "-----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-----"); } private static PrivateKey spPrivateKey() { return privateKey( "-----BEGIN PRIVATE KEY-----\n" + "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANG7v8QjQGU3MwQE\n" + "VUBxvH6Uuiy/MhZT7TV0ZNjyAF2ExA1gpn3aUxx6jYK5UnrpxRRE/KbeLucYbOhK\n" + "cDECt77Rggz5TStrOta0BQTvfluRyoQtmQ5Nkt6Vqg7O2ZapFt7k64Sal7AftzH6\n" + "Q2BxWN1y04bLdDrH4jipqRj/2qEFAgMBAAECgYEAj4ExY1jjdN3iEDuOwXuRB+Nn\n" + "x7pC4TgntE2huzdKvLJdGvIouTArce8A6JM5NlTBvm69mMepvAHgcsiMH1zGr5J5\n" + "wJz23mGOyhM1veON41/DJTVG+cxq4soUZhdYy3bpOuXGMAaJ8QLMbQQoivllNihd\n" + "vwH0rNSK8LTYWWPZYIECQQDxct+TFX1VsQ1eo41K0T4fu2rWUaxlvjUGhK6HxTmY\n" + "8OMJptunGRJL1CUjIb45Uz7SP8TPz5FwhXWsLfS182kRAkEA3l+Qd9C9gdpUh1uX\n" + "oPSNIxn5hFUrSTW1EwP9QH9vhwb5Vr8Jrd5ei678WYDLjUcx648RjkjhU9jSMzIx\n" + "EGvYtQJBAMm/i9NR7IVyyNIgZUpz5q4LI21rl1r4gUQuD8vA36zM81i4ROeuCly0\n" + "KkfdxR4PUfnKcQCX11YnHjk9uTFj75ECQEFY/gBnxDjzqyF35hAzrYIiMPQVfznt\n" + "YX/sDTE2AdVBVGaMj1Cb51bPHnNC6Q5kXKQnj/YrLqRQND09Q7ParX0CQQC5NxZr\n" + "9jKqhHj8yQD6PlXTsY4Occ7DH6/IoDenfdEVD5qlet0zmd50HatN2Jiqm5ubN7CM\n" + "INrtuLp4YHbgk1mi\n" + "-----END PRIVATE KEY-----"); } }
9,273
51.101124
109
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/DefaultSaml2AuthenticatedPrincipalMixinTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import static org.assertj.core.api.Assertions.assertThat; class DefaultSaml2AuthenticatedPrincipalMixinTests { private ObjectMapper mapper; @BeforeEach void setUp() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test void shouldSerialize() throws Exception { DefaultSaml2AuthenticatedPrincipal principal = TestSaml2JsonPayloads.createDefaultPrincipal(); String principalJson = this.mapper.writeValueAsString(principal); JSONAssert.assertEquals(TestSaml2JsonPayloads.DEFAULT_AUTHENTICATED_PRINCIPAL_JSON, principalJson, true); } @Test void shouldSerializeWithoutRegistrationId() throws Exception { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal( TestSaml2JsonPayloads.PRINCIPAL_NAME, TestSaml2JsonPayloads.ATTRIBUTES, TestSaml2JsonPayloads.SESSION_INDEXES); String principalJson = this.mapper.writeValueAsString(principal); JSONAssert.assertEquals(principalWithoutRegId(), principalJson, true); } @Test void shouldSerializeWithoutIndices() throws Exception { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal( TestSaml2JsonPayloads.PRINCIPAL_NAME, TestSaml2JsonPayloads.ATTRIBUTES); principal.setRelyingPartyRegistrationId(TestSaml2JsonPayloads.REG_ID); String principalJson = this.mapper.writeValueAsString(principal); JSONAssert.assertEquals(principalWithoutIndices(), principalJson, true); } @Test void shouldDeserialize() throws Exception { DefaultSaml2AuthenticatedPrincipal principal = this.mapper.readValue( TestSaml2JsonPayloads.DEFAULT_AUTHENTICATED_PRINCIPAL_JSON, DefaultSaml2AuthenticatedPrincipal.class); assertThat(principal).isNotNull(); assertThat(principal.getName()).isEqualTo(TestSaml2JsonPayloads.PRINCIPAL_NAME); assertThat(principal.getRelyingPartyRegistrationId()).isEqualTo(TestSaml2JsonPayloads.REG_ID); assertThat(principal.getAttributes()).isEqualTo(TestSaml2JsonPayloads.ATTRIBUTES); assertThat(principal.getSessionIndexes()).isEqualTo(TestSaml2JsonPayloads.SESSION_INDEXES); } @Test void shouldDeserializeWithoutRegistrationId() throws Exception { DefaultSaml2AuthenticatedPrincipal principal = this.mapper.readValue(principalWithoutRegId(), DefaultSaml2AuthenticatedPrincipal.class); assertThat(principal).isNotNull(); assertThat(principal.getName()).isEqualTo(TestSaml2JsonPayloads.PRINCIPAL_NAME); assertThat(principal.getRelyingPartyRegistrationId()).isNull(); assertThat(principal.getAttributes()).isEqualTo(TestSaml2JsonPayloads.ATTRIBUTES); assertThat(principal.getSessionIndexes()).isEqualTo(TestSaml2JsonPayloads.SESSION_INDEXES); } private static String principalWithoutRegId() { return TestSaml2JsonPayloads.DEFAULT_AUTHENTICATED_PRINCIPAL_JSON.replace(TestSaml2JsonPayloads.REG_ID_JSON, "null"); } private static String principalWithoutIndices() { return TestSaml2JsonPayloads.DEFAULT_AUTHENTICATED_PRINCIPAL_JSON .replace(TestSaml2JsonPayloads.SESSION_INDEXES_JSON, "[\"java.util.Collections$EmptyList\", []]"); } }
4,204
38.669811
110
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/Saml2PostAuthenticationRequestMixinTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import static org.assertj.core.api.Assertions.assertThat; class Saml2PostAuthenticationRequestMixinTests { private ObjectMapper mapper; @BeforeEach void setUp() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test void shouldSerialize() throws Exception { Saml2PostAuthenticationRequest request = TestSaml2JsonPayloads.createDefaultSaml2PostAuthenticationRequest(); String requestJson = this.mapper.writeValueAsString(request); JSONAssert.assertEquals(TestSaml2JsonPayloads.DEFAULT_POST_AUTH_REQUEST_JSON, requestJson, true); } @Test void shouldDeserialize() throws Exception { Saml2PostAuthenticationRequest authRequest = this.mapper .readValue(TestSaml2JsonPayloads.DEFAULT_POST_AUTH_REQUEST_JSON, Saml2PostAuthenticationRequest.class); assertThat(authRequest).isNotNull(); assertThat(authRequest.getSamlRequest()).isEqualTo(TestSaml2JsonPayloads.SAML_REQUEST); assertThat(authRequest.getRelayState()).isEqualTo(TestSaml2JsonPayloads.RELAY_STATE); assertThat(authRequest.getAuthenticationRequestUri()) .isEqualTo(TestSaml2JsonPayloads.AUTHENTICATION_REQUEST_URI); assertThat(authRequest.getRelyingPartyRegistrationId()) .isEqualTo(TestSaml2JsonPayloads.RELYINGPARTY_REGISTRATION_ID); assertThat(authRequest.getId()).isEqualTo(TestSaml2JsonPayloads.ID); } @Test void shouldDeserializeWithNoRegistrationId() throws Exception { String json = TestSaml2JsonPayloads.DEFAULT_POST_AUTH_REQUEST_JSON.replace( "\"relyingPartyRegistrationId\": \"" + TestSaml2JsonPayloads.RELYINGPARTY_REGISTRATION_ID + "\",", ""); Saml2PostAuthenticationRequest authRequest = this.mapper.readValue(json, Saml2PostAuthenticationRequest.class); assertThat(authRequest).isNotNull(); assertThat(authRequest.getSamlRequest()).isEqualTo(TestSaml2JsonPayloads.SAML_REQUEST); assertThat(authRequest.getRelayState()).isEqualTo(TestSaml2JsonPayloads.RELAY_STATE); assertThat(authRequest.getAuthenticationRequestUri()) .isEqualTo(TestSaml2JsonPayloads.AUTHENTICATION_REQUEST_URI); assertThat(authRequest.getRelyingPartyRegistrationId()).isNull(); assertThat(authRequest.getId()).isEqualTo(TestSaml2JsonPayloads.ID); } @Test void shouldDeserializeWithNoId() throws Exception { String json = TestSaml2JsonPayloads.DEFAULT_POST_AUTH_REQUEST_JSON .replace(", \"id\": \"" + TestSaml2JsonPayloads.ID + "\"", ""); Saml2PostAuthenticationRequest authRequest = this.mapper.readValue(json, Saml2PostAuthenticationRequest.class); assertThat(authRequest).isNotNull(); assertThat(authRequest.getSamlRequest()).isEqualTo(TestSaml2JsonPayloads.SAML_REQUEST); assertThat(authRequest.getRelayState()).isEqualTo(TestSaml2JsonPayloads.RELAY_STATE); assertThat(authRequest.getAuthenticationRequestUri()) .isEqualTo(TestSaml2JsonPayloads.AUTHENTICATION_REQUEST_URI); assertThat(authRequest.getRelyingPartyRegistrationId()) .isEqualTo(TestSaml2JsonPayloads.RELYINGPARTY_REGISTRATION_ID); assertThat(authRequest.getId()).isNull(); } }
4,141
41.265306
113
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/Saml2RedirectAuthenticationRequestMixinTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import static org.assertj.core.api.Assertions.assertThat; class Saml2RedirectAuthenticationRequestMixinTests { private ObjectMapper mapper; @BeforeEach void setUp() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test void shouldSerialize() throws Exception { Saml2RedirectAuthenticationRequest request = TestSaml2JsonPayloads .createDefaultSaml2RedirectAuthenticationRequest(); String requestJson = this.mapper.writeValueAsString(request); JSONAssert.assertEquals(TestSaml2JsonPayloads.DEFAULT_REDIRECT_AUTH_REQUEST_JSON, requestJson, true); } @Test void shouldDeserialize() throws Exception { Saml2RedirectAuthenticationRequest authRequest = this.mapper.readValue( TestSaml2JsonPayloads.DEFAULT_REDIRECT_AUTH_REQUEST_JSON, Saml2RedirectAuthenticationRequest.class); assertThat(authRequest).isNotNull(); assertThat(authRequest.getSamlRequest()).isEqualTo(TestSaml2JsonPayloads.SAML_REQUEST); assertThat(authRequest.getRelayState()).isEqualTo(TestSaml2JsonPayloads.RELAY_STATE); assertThat(authRequest.getAuthenticationRequestUri()) .isEqualTo(TestSaml2JsonPayloads.AUTHENTICATION_REQUEST_URI); assertThat(authRequest.getSigAlg()).isEqualTo(TestSaml2JsonPayloads.SIG_ALG); assertThat(authRequest.getSignature()).isEqualTo(TestSaml2JsonPayloads.SIGNATURE); assertThat(authRequest.getRelyingPartyRegistrationId()) .isEqualTo(TestSaml2JsonPayloads.RELYINGPARTY_REGISTRATION_ID); } @Test void shouldDeserializeWithNoRegistrationId() throws Exception { String json = TestSaml2JsonPayloads.DEFAULT_REDIRECT_AUTH_REQUEST_JSON.replace( "\"relyingPartyRegistrationId\": \"" + TestSaml2JsonPayloads.RELYINGPARTY_REGISTRATION_ID + "\",", ""); Saml2RedirectAuthenticationRequest authRequest = this.mapper.readValue(json, Saml2RedirectAuthenticationRequest.class); assertThat(authRequest).isNotNull(); assertThat(authRequest.getSamlRequest()).isEqualTo(TestSaml2JsonPayloads.SAML_REQUEST); assertThat(authRequest.getRelayState()).isEqualTo(TestSaml2JsonPayloads.RELAY_STATE); assertThat(authRequest.getAuthenticationRequestUri()) .isEqualTo(TestSaml2JsonPayloads.AUTHENTICATION_REQUEST_URI); assertThat(authRequest.getSigAlg()).isEqualTo(TestSaml2JsonPayloads.SIG_ALG); assertThat(authRequest.getSignature()).isEqualTo(TestSaml2JsonPayloads.SIGNATURE); assertThat(authRequest.getRelyingPartyRegistrationId()).isNull(); } }
3,556
40.847059
109
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/Saml2AuthenticationExceptionMixinTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import static org.assertj.core.api.Assertions.assertThat; class Saml2AuthenticationExceptionMixinTests { private ObjectMapper mapper; @BeforeEach void setUp() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test void shouldSerialize() throws Exception { Saml2AuthenticationException exception = TestSaml2JsonPayloads.createDefaultSaml2AuthenticationException(); String exceptionJson = this.mapper.writeValueAsString(exception); JSONAssert.assertEquals(TestSaml2JsonPayloads.DEFAULT_SAML_AUTH_EXCEPTION_JSON, exceptionJson, true); } @Test void shouldDeserialize() throws Exception { Saml2AuthenticationException exception = this.mapper .readValue(TestSaml2JsonPayloads.DEFAULT_SAML_AUTH_EXCEPTION_JSON, Saml2AuthenticationException.class); assertThat(exception).isNotNull(); assertThat(exception.getMessage()).isEqualTo("exceptionMessage"); assertThat(exception.getSaml2Error()).extracting(Saml2Error::getErrorCode, Saml2Error::getDescription) .contains("errorCode", "errorDescription"); } }
2,238
35.112903
109
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/TestSaml2JsonPayloads.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.User; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; final class TestSaml2JsonPayloads { private TestSaml2JsonPayloads() { } static final Map<String, List<Object>> ATTRIBUTES; static { Map<String, List<Object>> tmpAttributes = new HashMap<>(); tmpAttributes.put("name", Collections.singletonList("attr_name")); tmpAttributes.put("email", Collections.singletonList("attr_email")); tmpAttributes.put("listOf", Collections.unmodifiableList(Arrays.asList("Element1", "Element2", 4, true))); ATTRIBUTES = Collections.unmodifiableMap(tmpAttributes); } static final String REG_ID = "REG_ID_TEST"; static final String REG_ID_JSON = "\"" + REG_ID + "\""; static final String SESSION_INDEXES_JSON = "[" + " \"java.util.Collections$UnmodifiableRandomAccessList\"," + " [ \"Index 1\", \"Index 2\" ]" + "]"; static final List<String> SESSION_INDEXES = Collections.unmodifiableList(Arrays.asList("Index 1", "Index 2")); static final String PRINCIPAL_NAME = "principalName"; // @formatter:off static final String DEFAULT_AUTHENTICATED_PRINCIPAL_JSON = "{" + " \"@class\": \"org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal\"," + " \"name\": \"" + PRINCIPAL_NAME + "\"," + " \"attributes\": {" + " \"@class\": \"java.util.Collections$UnmodifiableMap\"," + " \"listOf\": [" + " \"java.util.Collections$UnmodifiableRandomAccessList\"," + " [ \"Element1\", \"Element2\", 4, true ]" + " ]," + " \"email\": [" + " \"java.util.Collections$SingletonList\"," + " [ \"attr_email\" ]" + " ]," + " \"name\": [" + " \"java.util.Collections$SingletonList\"," + " [ \"attr_name\" ]" + " ]" + " }," + " \"sessionIndexes\": " + SESSION_INDEXES_JSON + "," + " \"registrationId\": " + REG_ID_JSON + "" + "}"; // @formatter:on static DefaultSaml2AuthenticatedPrincipal createDefaultPrincipal() { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal(PRINCIPAL_NAME, ATTRIBUTES, SESSION_INDEXES); principal.setRelyingPartyRegistrationId(REG_ID); return principal; } static final String SAML_REQUEST = "samlRequestValue"; static final String RELAY_STATE = "relayStateValue"; static final String AUTHENTICATION_REQUEST_URI = "authenticationRequestUriValue"; static final String RELYINGPARTY_REGISTRATION_ID = "registrationIdValue"; static final String SIG_ALG = "sigAlgValue"; static final String SIGNATURE = "signatureValue"; static final String ID = "idValue"; // @formatter:off static final String DEFAULT_REDIRECT_AUTH_REQUEST_JSON = "{" + " \"@class\": \"org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest\"," + " \"samlRequest\": \"" + SAML_REQUEST + "\"," + " \"relayState\": \"" + RELAY_STATE + "\"," + " \"authenticationRequestUri\": \"" + AUTHENTICATION_REQUEST_URI + "\"," + " \"relyingPartyRegistrationId\": \"" + RELYINGPARTY_REGISTRATION_ID + "\"," + " \"sigAlg\": \"" + SIG_ALG + "\"," + " \"signature\": \"" + SIGNATURE + "\"," + " \"id\": \"" + ID + "\"" + "}"; // @formatter:on // @formatter:off static final String DEFAULT_POST_AUTH_REQUEST_JSON = "{" + " \"@class\": \"org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest\"," + " \"samlRequest\": \"" + SAML_REQUEST + "\"," + " \"relayState\": \"" + RELAY_STATE + "\"," + " \"relyingPartyRegistrationId\": \"" + RELYINGPARTY_REGISTRATION_ID + "\"," + " \"authenticationRequestUri\": \"" + AUTHENTICATION_REQUEST_URI + "\"," + " \"id\": \"" + ID + "\"" + "}"; // @formatter:on static final String LOCATION = "locationValue"; static final String BINDNG = "REDIRECT"; static final String ADDITIONAL_PARAM = "additionalParamValue"; // @formatter:off static final String DEFAULT_LOGOUT_REQUEST_JSON = "{" + " \"@class\": \"org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest\"," + " \"id\": \"" + ID + "\"," + " \"location\": \"" + LOCATION + "\"," + " \"binding\": \"" + BINDNG + "\"," + " \"relyingPartyRegistrationId\": \"" + RELYINGPARTY_REGISTRATION_ID + "\"," + " \"parameters\": { " + " \"@class\": \"java.util.Collections$UnmodifiableMap\"," + " \"SAMLRequest\": \"" + SAML_REQUEST + "\"," + " \"RelayState\": \"" + RELAY_STATE + "\"," + " \"AdditionalParam\": \"" + ADDITIONAL_PARAM + "\"" + " }" + "}"; // @formatter:on static Saml2PostAuthenticationRequest createDefaultSaml2PostAuthenticationRequest() { return Saml2PostAuthenticationRequest.withRelyingPartyRegistration( TestRelyingPartyRegistrations.full().registrationId(RELYINGPARTY_REGISTRATION_ID) .assertingPartyDetails((party) -> party.singleSignOnServiceLocation(AUTHENTICATION_REQUEST_URI)) .build()) .samlRequest(SAML_REQUEST).relayState(RELAY_STATE).id(ID).build(); } static Saml2RedirectAuthenticationRequest createDefaultSaml2RedirectAuthenticationRequest() { return Saml2RedirectAuthenticationRequest .withRelyingPartyRegistration(TestRelyingPartyRegistrations.full() .registrationId(RELYINGPARTY_REGISTRATION_ID) .assertingPartyDetails((party) -> party.singleSignOnServiceLocation(AUTHENTICATION_REQUEST_URI)) .build()) .samlRequest(SAML_REQUEST).relayState(RELAY_STATE).sigAlg(SIG_ALG).signature(SIGNATURE).id(ID).build(); } static Saml2LogoutRequest createDefaultSaml2LogoutRequest() { return Saml2LogoutRequest .withRelyingPartyRegistration( TestRelyingPartyRegistrations.full().registrationId(RELYINGPARTY_REGISTRATION_ID) .assertingPartyDetails((party) -> party.singleLogoutServiceLocation(LOCATION) .singleLogoutServiceBinding(Saml2MessageBinding.REDIRECT)) .build()) .id(ID).samlRequest(SAML_REQUEST).relayState(RELAY_STATE) .parameters((params) -> params.put("AdditionalParam", ADDITIONAL_PARAM)).build(); } static final Collection<GrantedAuthority> AUTHORITIES = Collections .unmodifiableList(Arrays.asList(new SimpleGrantedAuthority("Role1"), new SimpleGrantedAuthority("Role2"))); static final Object DETAILS = User.withUsername("username").password("empty").authorities("A", "B").build(); static final String SAML_RESPONSE = "samlResponseValue"; // @formatter:off static final String DEFAULT_SAML2AUTHENTICATION_JSON = "{" + " \"@class\": \"org.springframework.security.saml2.provider.service.authentication.Saml2Authentication\"," + " \"authorities\": [" + " \"java.util.Collections$UnmodifiableRandomAccessList\"," + " [" + " {" + " \"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"," + " \"authority\": \"Role1\"" + " }," + " {" + " \"@class\": \"org.springframework.security.core.authority.SimpleGrantedAuthority\"," + " \"authority\": \"Role2\"" + " }" + " ]" + " ]," + " \"details\": {" + " \"@class\": \"org.springframework.security.core.userdetails.User\"," + " \"password\": \"empty\"," + " \"username\": \"username\"," + " \"authorities\": [" + " \"java.util.Collections$UnmodifiableSet\", [" + " {" + " \"@class\":\"org.springframework.security.core.authority.SimpleGrantedAuthority\"," + " \"authority\":\"A\"" + " }," + " {" + " \"@class\":\"org.springframework.security.core.authority.SimpleGrantedAuthority\"," + " \"authority\":\"B\"" + " }" + " ]]," + " \"accountNonExpired\": true," + " \"accountNonLocked\": true," + " \"credentialsNonExpired\": true," + " \"enabled\": true" + " }," + " \"principal\": " + DEFAULT_AUTHENTICATED_PRINCIPAL_JSON + "," + " \"saml2Response\": \"" + SAML_RESPONSE + "\"" + "}"; // @formatter:on static Saml2Authentication createDefaultAuthentication() { DefaultSaml2AuthenticatedPrincipal principal = createDefaultPrincipal(); Saml2Authentication authentication = new Saml2Authentication(principal, SAML_RESPONSE, AUTHORITIES); authentication.setDetails(DETAILS); return authentication; } // @formatter:off static final String DEFAULT_SAML_AUTH_EXCEPTION_JSON = "{" + " \"@class\": \"org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException\"," + " \"detailMessage\": \"exceptionMessage\"," + " \"error\": {" + " \"@class\": \"org.springframework.security.saml2.core.Saml2Error\"," + " \"errorCode\": \"errorCode\"," + " \"description\": \"errorDescription\"" + " }" + "}"; // @formatter:on static Saml2AuthenticationException createDefaultSaml2AuthenticationException() { return new Saml2AuthenticationException(new Saml2Error("errorCode", "errorDescription"), "exceptionMessage"); } }
10,745
42.861224
127
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/Saml2LogoutRequestMixinTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import static org.assertj.core.api.Assertions.assertThat; class Saml2LogoutRequestMixinTests { private ObjectMapper mapper; @BeforeEach void setUp() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test void shouldSerialize() throws Exception { Saml2LogoutRequest request = TestSaml2JsonPayloads.createDefaultSaml2LogoutRequest(); String requestJson = this.mapper.writeValueAsString(request); JSONAssert.assertEquals(TestSaml2JsonPayloads.DEFAULT_LOGOUT_REQUEST_JSON, requestJson, true); } @Test void shouldDeserialize() throws Exception { Saml2LogoutRequest logoutRequest = this.mapper.readValue(TestSaml2JsonPayloads.DEFAULT_LOGOUT_REQUEST_JSON, Saml2LogoutRequest.class); assertThat(logoutRequest).isNotNull(); assertThat(logoutRequest.getId()).isEqualTo(TestSaml2JsonPayloads.ID); assertThat(logoutRequest.getRelyingPartyRegistrationId()) .isEqualTo(TestSaml2JsonPayloads.RELYINGPARTY_REGISTRATION_ID); assertThat(logoutRequest.getSamlRequest()).isEqualTo(TestSaml2JsonPayloads.SAML_REQUEST); assertThat(logoutRequest.getRelayState()).isEqualTo(TestSaml2JsonPayloads.RELAY_STATE); assertThat(logoutRequest.getLocation()).isEqualTo(TestSaml2JsonPayloads.LOCATION); assertThat(logoutRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); Map<String, String> expectedParams = new HashMap<>(); expectedParams.put("SAMLRequest", TestSaml2JsonPayloads.SAML_REQUEST); expectedParams.put("RelayState", TestSaml2JsonPayloads.RELAY_STATE); expectedParams.put("AdditionalParam", TestSaml2JsonPayloads.ADDITIONAL_PARAM); assertThat(logoutRequest.getParameters()).containsAllEntriesOf(expectedParams); } }
2,949
38.864865
109
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/jackson2/Saml2AuthenticationMixinTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import static org.assertj.core.api.Assertions.assertThat; class Saml2AuthenticationMixinTests { private ObjectMapper mapper; @BeforeEach void setUp() { this.mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); this.mapper.registerModules(SecurityJackson2Modules.getModules(loader)); } @Test void shouldSerialize() throws Exception { Saml2Authentication authentication = TestSaml2JsonPayloads.createDefaultAuthentication(); String authenticationJson = this.mapper.writeValueAsString(authentication); JSONAssert.assertEquals(TestSaml2JsonPayloads.DEFAULT_SAML2AUTHENTICATION_JSON, authenticationJson, true); } @Test void shouldDeserialize() throws Exception { Saml2Authentication authentication = this.mapper .readValue(TestSaml2JsonPayloads.DEFAULT_SAML2AUTHENTICATION_JSON, Saml2Authentication.class); assertThat(authentication).isNotNull(); assertThat(authentication.getDetails()).isEqualTo(TestSaml2JsonPayloads.DETAILS); assertThat(authentication.getCredentials()).isEqualTo(TestSaml2JsonPayloads.SAML_RESPONSE); assertThat(authentication.getSaml2Response()).isEqualTo(TestSaml2JsonPayloads.SAML_RESPONSE); assertThat(authentication.getAuthorities()).isEqualTo(TestSaml2JsonPayloads.AUTHORITIES); assertThat(authentication.getPrincipal()).usingRecursiveComparison() .isEqualTo(TestSaml2JsonPayloads.createDefaultPrincipal()); assertThat(authentication.getDetails()).usingRecursiveComparison().isEqualTo(TestSaml2JsonPayloads.DETAILS); } }
2,541
38.107692
110
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/InMemoryRelyingPartyRegistrationRepositoryTests.java
/* * 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.registration; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link InMemoryRelyingPartyRegistrationRepository} */ public class InMemoryRelyingPartyRegistrationRepositoryTests { @Test void findByRegistrationIdWhenGivenIdThenReturnsMatchingRegistration() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); InMemoryRelyingPartyRegistrationRepository registrations = new InMemoryRelyingPartyRegistrationRepository( registration); assertThat(registrations.findByRegistrationId(registration.getRegistrationId())).isSameAs(registration); } @Test void findByRegistrationIdWhenGivenWrongIdThenReturnsNull() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); InMemoryRelyingPartyRegistrationRepository registrations = new InMemoryRelyingPartyRegistrationRepository( registration); assertThat(registrations.findByRegistrationId(registration.getRegistrationId() + "wrong")).isNull(); assertThat(registrations.findByRegistrationId(null)).isNull(); } @Test void findByAssertingPartyEntityIdWhenGivenEntityIdThenReturnsMatchingRegistrations() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); InMemoryRelyingPartyRegistrationRepository registrations = new InMemoryRelyingPartyRegistrationRepository( registration); String assertingPartyEntityId = registration.getAssertingPartyDetails().getEntityId(); assertThat(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId)).isEqualTo(registration); } @Test void findByAssertingPartyEntityIdWhenGivenWrongEntityIdThenReturnsEmpty() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); InMemoryRelyingPartyRegistrationRepository registrations = new InMemoryRelyingPartyRegistrationRepository( registration); String assertingPartyEntityId = registration.getAssertingPartyDetails().getEntityId(); assertThat(registrations.findUniqueByAssertingPartyEntityId(assertingPartyEntityId + "wrong")).isNull(); } }
2,891
44.1875
111
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlMetadataRelyingPartyRegistrationConverterTests.java
/* * 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.registration; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Base64; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.springframework.core.io.ClassPathResource; import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class OpenSamlMetadataRelyingPartyRegistrationConverterTests { private static final String CERTIFICATE = "MIIEEzCCAvugAwIBAgIJAIc1qzLrv+5nMA0GCSqGSIb3DQEBCwUAMIGfMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ08xFDASBgNVBAcMC0Nhc3RsZSBSb2NrMRwwGgYDVQQKDBNTYW1sIFRlc3RpbmcgU2VydmVyMQswCQYDVQQLDAJJVDEgMB4GA1UEAwwXc2ltcGxlc2FtbHBocC5jZmFwcHMuaW8xIDAeBgkqhkiG9w0BCQEWEWZoYW5pa0BwaXZvdGFsLmlvMB4XDTE1MDIyMzIyNDUwM1oXDTI1MDIyMjIyNDUwM1owgZ8xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDTzEUMBIGA1UEBwwLQ2FzdGxlIFJvY2sxHDAaBgNVBAoME1NhbWwgVGVzdGluZyBTZXJ2ZXIxCzAJBgNVBAsMAklUMSAwHgYDVQQDDBdzaW1wbGVzYW1scGhwLmNmYXBwcy5pbzEgMB4GCSqGSIb3DQEJARYRZmhhbmlrQHBpdm90YWwuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4cn62E1xLqpN34PmbrKBbkOXFjzWgJ9b+pXuaRft6A339uuIQeoeH5qeSKRVTl32L0gdz2ZivLwZXW+cqvftVW1tvEHvzJFyxeTW3fCUeCQsebLnA2qRa07RkxTo6Nf244mWWRDodcoHEfDUSbxfTZ6IExSojSIU2RnD6WllYWFdD1GFpBJOmQB8rAc8wJIBdHFdQnX8Ttl7hZ6rtgqEYMzYVMuJ2F2r1HSU1zSAvwpdYP6rRGFRJEfdA9mm3WKfNLSc5cljz0X/TXy0vVlAV95l9qcfFzPmrkNIst9FZSwpvB49LyAVke04FQPPwLgVH4gphiJH3jvZ7I+J5lS8VAgMBAAGjUDBOMB0GA1UdDgQWBBTTyP6Cc5HlBJ5+ucVCwGc5ogKNGzAfBgNVHSMEGDAWgBTTyP6Cc5HlBJ5+ucVCwGc5ogKNGzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAvMS4EQeP/ipV4jOG5lO6/tYCb/iJeAduOnRhkJk0DbX329lDLZhTTL/x/w/9muCVcvLrzEp6PN+VWfw5E5FWtZN0yhGtP9R+vZnrV+oc2zGD+no1/ySFOe3EiJCO5dehxKjYEmBRv5sU/LZFKZpozKN/BMEa6CqLuxbzb7ykxVr7EVFXwltPxzE9TmL9OACNNyF5eJHWMRMllarUvkcXlh4pux4ks9e6zV9DQBy2zds9f1I3qxg0eX6JnGrXi/ZiCT+lJgVe3ZFXiejiLAiKB04sXW3ti0LW3lx13Y1YlQ4/tlpgTgfIJxKV6nyPiLoK0nywbMd+vpAirDt2Oc+hk"; private static final String ENTITIES_DESCRIPTOR_TEMPLATE = "<md:EntitiesDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\">\n%s</md:EntitiesDescriptor>"; private static final String ENTITY_DESCRIPTOR_TEMPLATE = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" " + "xmlns:alg=\"urn:oasis:names:tc:SAML:metadata:algsupport\" " + "entityID=\"entity-id\" " + "ID=\"_bf133aac099b99b3d81286e1a341f2d34188043a77fe15bf4bf1487dae9b2ea3\">\n%s" + "</md:EntityDescriptor>"; private static final String IDP_SSO_DESCRIPTOR_TEMPLATE = "<md:IDPSSODescriptor protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\">\n" + "%s\n" + "</md:IDPSSODescriptor>"; private static final String KEY_DESCRIPTOR_TEMPLATE = "<md:KeyDescriptor %s>\n" + "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + "<ds:X509Data>\n" + "<ds:X509Certificate>" + CERTIFICATE + "</ds:X509Certificate>\n" + "</ds:X509Data>\n" + "</ds:KeyInfo>\n" + "</md:KeyDescriptor>"; private static final String EXTENSIONS_TEMPLATE = "<md:Extensions>" + "<alg:SigningMethod Algorithm=\"" + SignatureConstants.ALGO_ID_DIGEST_SHA512 + "\"/>" + "</md:Extensions>"; private static final String SINGLE_SIGN_ON_SERVICE_TEMPLATE = "<md:SingleSignOnService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" " + "Location=\"sso-location\"/>"; private OpenSamlMetadataRelyingPartyRegistrationConverter converter = new OpenSamlMetadataRelyingPartyRegistrationConverter(); private String metadata; @BeforeEach public void setup() throws Exception { ClassPathResource resource = new ClassPathResource("test-metadata.xml"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) { this.metadata = reader.lines().collect(Collectors.joining()); } } // gh-12667 @Test public void convertWhenDefaultsThenAssertingPartyInstanceOfOpenSaml() throws Exception { try (InputStream source = new ByteArrayInputStream(this.metadata.getBytes(StandardCharsets.UTF_8))) { this.converter.convert(source) .forEach((registration) -> assertThat(registration.build().getAssertingPartyDetails()) .isInstanceOf(OpenSamlAssertingPartyDetails.class)); } } @Test public void readWhenMissingIDPSSODescriptorThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, ""); InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> this.converter.convert(inputStream)) .withMessageContaining("Metadata response is missing the necessary IDPSSODescriptor element"); } @Test public void readWhenMissingVerificationKeyThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, "")); InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> this.converter.convert(inputStream)) .withMessageContaining( "Metadata response is missing verification certificates, necessary for verifying SAML assertions"); } @Test public void readWhenMissingSingleSignOnServiceThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\""))); InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> this.converter.convert(inputStream)) .withMessageContaining( "Metadata response is missing a SingleSignOnService, necessary for sending AuthnRequests"); } @Test public void readWhenDescriptorFullySpecifiedThenConfigures() throws Exception { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\"") + String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"encryption\"") + EXTENSIONS_TEMPLATE + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE))); InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); RelyingPartyRegistration.AssertingPartyDetails details = this.converter.convert(inputStream).iterator().next() .build().getAssertingPartyDetails(); assertThat(details.getWantAuthnRequestsSigned()).isFalse(); assertThat(details.getSigningAlgorithms()).containsExactly(SignatureConstants.ALGO_ID_DIGEST_SHA512); assertThat(details.getSingleSignOnServiceLocation()).isEqualTo("sso-location"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(details.getEntityId()).isEqualTo("entity-id"); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getVerificationX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details.getEncryptionX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details).isInstanceOf(OpenSamlAssertingPartyDetails.class); OpenSamlAssertingPartyDetails openSamlDetails = (OpenSamlAssertingPartyDetails) details; EntityDescriptor entityDescriptor = openSamlDetails.getEntityDescriptor(); assertThat(entityDescriptor).isNotNull(); assertThat(entityDescriptor.getEntityID()).isEqualTo(details.getEntityId()); } // gh-9051 @Test public void readWhenEntitiesDescriptorThenConfigures() throws Exception { String payload = String.format(ENTITIES_DESCRIPTOR_TEMPLATE, String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\"") + String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"encryption\"") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE)))); InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); RelyingPartyRegistration.AssertingPartyDetails details = this.converter.convert(inputStream).iterator().next() .build().getAssertingPartyDetails(); assertThat(details.getWantAuthnRequestsSigned()).isFalse(); assertThat(details.getSingleSignOnServiceLocation()).isEqualTo("sso-location"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(details.getEntityId()).isEqualTo("entity-id"); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getVerificationX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details.getEncryptionX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); } @Test public void readWhenKeyDescriptorHasNoUseThenConfiguresBothKeyTypes() throws Exception { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE))); InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); RelyingPartyRegistration.AssertingPartyDetails details = this.converter.convert(inputStream).iterator().next() .build().getAssertingPartyDetails(); assertThat(details.getVerificationX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details.getEncryptionX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); } X509Certificate x509Certificate(String data) { try { InputStream certificate = new ByteArrayInputStream(Base64.getDecoder().decode(data.getBytes())); return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certificate); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } // gh-9051 @Test public void readWhenUnsupportedElementThenSaml2Exception() { String payload = "<saml2:Assertion xmlns:saml2=\"https://some.endpoint\"/>"; InputStream inputStream = new ByteArrayInputStream(payload.getBytes()); assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> this.converter.convert(inputStream)) .withMessage("Unsupported element of type saml2:Assertion"); } }
11,510
56.555
1,442
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationsTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.registration; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.io.ClassPathResource; import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link RelyingPartyRegistration} */ public class RelyingPartyRegistrationsTests { private String metadata; private String entitiesDescriptor; @BeforeEach public void setup() throws Exception { ClassPathResource resource = new ClassPathResource("test-metadata.xml"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) { this.metadata = reader.lines().collect(Collectors.joining()); } resource = new ClassPathResource("test-entitiesdescriptor.xml"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) { this.entitiesDescriptor = reader.lines().collect(Collectors.joining()); } } @Test public void fromMetadataUrlLocationWhenResolvableThenPopulatesBuilder() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody(this.metadata).setResponseCode(200)); RelyingPartyRegistration registration = RelyingPartyRegistrations .fromMetadataLocation(server.url("/").toString()).entityId("rp").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } } @Test public void fromMetadataUrlLocationWhenUnresolvableThenSaml2Exception() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody(this.metadata).setResponseCode(200)); String url = server.url("/").toString(); server.shutdown(); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.fromMetadataLocation(url)); } } @Test public void fromMetadataUrlLocationWhenMalformedResponseThenSaml2Exception() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody("malformed").setResponseCode(200)); String url = server.url("/").toString(); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.fromMetadataLocation(url)); } } @Test public void fromMetadataFileLocationWhenResolvableThenPopulatesBuilder() { File file = new File("src/test/resources/test-metadata.xml"); RelyingPartyRegistration registration = RelyingPartyRegistrations .fromMetadataLocation("file:" + file.getAbsolutePath()).entityId("rp").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } @Test public void fromMetadataFileLocationWhenNotFoundThenSaml2Exception() { assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.fromMetadataLocation("filePath")); } @Test public void fromMetadataInputStreamWhenResolvableThenPopulatesBuilder() throws Exception { try (InputStream source = new ByteArrayInputStream(this.metadata.getBytes())) { RelyingPartyRegistration registration = RelyingPartyRegistrations.fromMetadata(source).entityId("rp") .build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } } @Test public void fromMetadataInputStreamWhenEmptyThenSaml2Exception() throws Exception { try (InputStream source = new ByteArrayInputStream("".getBytes())) { assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.fromMetadata(source)); } } @Test public void collectionFromMetadataLocationWhenResolvableThenPopulatesBuilder() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody(this.entitiesDescriptor).setResponseCode(200)); List<RelyingPartyRegistration> registrations = RelyingPartyRegistrations .collectionFromMetadataLocation(server.url("/").toString()).stream() .map((r) -> r.entityId("rp").build()).collect(Collectors.toList()); assertThat(registrations).hasSize(2); RelyingPartyRegistration first = registrations.get(0); RelyingPartyRegistration.AssertingPartyDetails details = first.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); RelyingPartyRegistration second = registrations.get(1); details = second.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://ap.example.org/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://ap.example.org/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } } @Test public void collectionFromMetadataLocationWhenUnresolvableThenSaml2Exception() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody(this.metadata).setResponseCode(200)); String url = server.url("/").toString(); server.shutdown(); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.collectionFromMetadataLocation(url)); } } @Test public void collectionFromMetadataLocationWhenMalformedResponseThenSaml2Exception() throws Exception { try (MockWebServer server = new MockWebServer()) { server.enqueue(new MockResponse().setBody("malformed").setResponseCode(200)); String url = server.url("/").toString(); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.collectionFromMetadataLocation(url)); } } @Test public void collectionFromMetadataFileWhenResolvableThenPopulatesBuilder() { File file = new File("src/test/resources/test-entitiesdescriptor.xml"); RelyingPartyRegistration registration = RelyingPartyRegistrations .collectionFromMetadataLocation("file:" + file.getAbsolutePath()).stream() .map((r) -> r.entityId("rp").build()).findFirst().get(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } @Test public void collectionFromMetadataFileWhenContainsOnlyEntityDescriptorThenPopulatesBuilder() { File file = new File("src/test/resources/test-metadata.xml"); RelyingPartyRegistration registration = RelyingPartyRegistrations .collectionFromMetadataLocation("file:" + file.getAbsolutePath()).stream() .map((r) -> r.entityId("rp").build()).findFirst().get(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } @Test public void collectionFromMetadataFileWhenNotFoundThenSaml2Exception() { assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.collectionFromMetadataLocation("filePath")); } @Test public void collectionFromMetadataInputStreamWhenResolvableThenPopulatesBuilder() throws Exception { try (InputStream source = new ByteArrayInputStream(this.entitiesDescriptor.getBytes())) { RelyingPartyRegistration registration = RelyingPartyRegistrations.collectionFromMetadata(source).stream() .map((r) -> r.entityId("rp").build()).findFirst().get(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getEntityId()).isEqualTo("https://idp.example.com/idp/shibboleth"); assertThat(details.getSingleSignOnServiceLocation()) .isEqualTo("https://idp.example.com/idp/profile/SAML2/POST/SSO"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials()).hasSize(1); } } @Test public void collectionFromMetadataInputStreamWhenEmptyThenSaml2Exception() throws Exception { try (InputStream source = new ByteArrayInputStream("".getBytes())) { assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> RelyingPartyRegistrations.collectionFromMetadata(source)); } } @Test public void collectionFromMetadataLocationCanHandleFederationMetadata() { Collection<RelyingPartyRegistration.Builder> federationMetadataWithSkippedSPEntries = RelyingPartyRegistrations .collectionFromMetadataLocation("classpath:test-federated-metadata.xml"); assertThat(federationMetadataWithSkippedSPEntries.size()).isEqualTo(1); } @Test public void collectionFromMetadataLocationWithoutIdpThenSaml2Exception() { assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> RelyingPartyRegistrations .collectionFromMetadataLocation("classpath:test-metadata-without-idp.xml")); } }
12,519
46.969349
113
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests.java
/* * 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.provider.service.registration; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Base64; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.mock.http.client.MockClientHttpResponse; import org.springframework.security.saml2.Saml2Exception; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverterTests { private static final String CERTIFICATE = "MIIEEzCCAvugAwIBAgIJAIc1qzLrv+5nMA0GCSqGSIb3DQEBCwUAMIGfMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ08xFDASBgNVBAcMC0Nhc3RsZSBSb2NrMRwwGgYDVQQKDBNTYW1sIFRlc3RpbmcgU2VydmVyMQswCQYDVQQLDAJJVDEgMB4GA1UEAwwXc2ltcGxlc2FtbHBocC5jZmFwcHMuaW8xIDAeBgkqhkiG9w0BCQEWEWZoYW5pa0BwaXZvdGFsLmlvMB4XDTE1MDIyMzIyNDUwM1oXDTI1MDIyMjIyNDUwM1owgZ8xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDTzEUMBIGA1UEBwwLQ2FzdGxlIFJvY2sxHDAaBgNVBAoME1NhbWwgVGVzdGluZyBTZXJ2ZXIxCzAJBgNVBAsMAklUMSAwHgYDVQQDDBdzaW1wbGVzYW1scGhwLmNmYXBwcy5pbzEgMB4GCSqGSIb3DQEJARYRZmhhbmlrQHBpdm90YWwuaW8wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4cn62E1xLqpN34PmbrKBbkOXFjzWgJ9b+pXuaRft6A339uuIQeoeH5qeSKRVTl32L0gdz2ZivLwZXW+cqvftVW1tvEHvzJFyxeTW3fCUeCQsebLnA2qRa07RkxTo6Nf244mWWRDodcoHEfDUSbxfTZ6IExSojSIU2RnD6WllYWFdD1GFpBJOmQB8rAc8wJIBdHFdQnX8Ttl7hZ6rtgqEYMzYVMuJ2F2r1HSU1zSAvwpdYP6rRGFRJEfdA9mm3WKfNLSc5cljz0X/TXy0vVlAV95l9qcfFzPmrkNIst9FZSwpvB49LyAVke04FQPPwLgVH4gphiJH3jvZ7I+J5lS8VAgMBAAGjUDBOMB0GA1UdDgQWBBTTyP6Cc5HlBJ5+ucVCwGc5ogKNGzAfBgNVHSMEGDAWgBTTyP6Cc5HlBJ5+ucVCwGc5ogKNGzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAvMS4EQeP/ipV4jOG5lO6/tYCb/iJeAduOnRhkJk0DbX329lDLZhTTL/x/w/9muCVcvLrzEp6PN+VWfw5E5FWtZN0yhGtP9R+vZnrV+oc2zGD+no1/ySFOe3EiJCO5dehxKjYEmBRv5sU/LZFKZpozKN/BMEa6CqLuxbzb7ykxVr7EVFXwltPxzE9TmL9OACNNyF5eJHWMRMllarUvkcXlh4pux4ks9e6zV9DQBy2zds9f1I3qxg0eX6JnGrXi/ZiCT+lJgVe3ZFXiejiLAiKB04sXW3ti0LW3lx13Y1YlQ4/tlpgTgfIJxKV6nyPiLoK0nywbMd+vpAirDt2Oc+hk"; private static final String ENTITIES_DESCRIPTOR_TEMPLATE = "<md:EntitiesDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\">\n%s</md:EntitiesDescriptor>"; private static final String ENTITY_DESCRIPTOR_TEMPLATE = "<md:EntityDescriptor xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" " + "entityID=\"entity-id\" " + "ID=\"_bf133aac099b99b3d81286e1a341f2d34188043a77fe15bf4bf1487dae9b2ea3\">\n%s" + "</md:EntityDescriptor>"; private static final String IDP_SSO_DESCRIPTOR_TEMPLATE = "<md:IDPSSODescriptor protocolSupportEnumeration=\"urn:oasis:names:tc:SAML:2.0:protocol\">\n" + "%s\n" + "</md:IDPSSODescriptor>"; private static final String KEY_DESCRIPTOR_TEMPLATE = "<md:KeyDescriptor %s>\n" + "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + "<ds:X509Data>\n" + "<ds:X509Certificate>" + CERTIFICATE + "</ds:X509Certificate>\n" + "</ds:X509Data>\n" + "</ds:KeyInfo>\n" + "</md:KeyDescriptor>"; private static final String SINGLE_SIGN_ON_SERVICE_TEMPLATE = "<md:SingleSignOnService Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\" " + "Location=\"sso-location\"/>"; private OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter converter; @BeforeEach public void setup() { this.converter = new OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter(); } @Test public void readWhenMissingIDPSSODescriptorThenException() { MockClientHttpResponse response = new MockClientHttpResponse( (String.format(ENTITY_DESCRIPTOR_TEMPLATE, "")).getBytes(), HttpStatus.OK); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .withMessageContaining("Metadata response is missing the necessary IDPSSODescriptor element"); } @Test public void readWhenMissingVerificationKeyThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, "")); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .withMessageContaining( "Metadata response is missing verification certificates, necessary for verifying SAML assertions"); } @Test public void readWhenMissingSingleSignOnServiceThenException() { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\""))); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .withMessageContaining( "Metadata response is missing a SingleSignOnService, necessary for sending AuthnRequests"); } @Test public void readWhenDescriptorFullySpecifiedThenConfigures() throws Exception { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\"") + String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"encryption\"") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE))); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); RelyingPartyRegistration registration = this.converter.read(RelyingPartyRegistration.Builder.class, response) .registrationId("one").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getWantAuthnRequestsSigned()).isFalse(); assertThat(details.getSingleSignOnServiceLocation()).isEqualTo("sso-location"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(details.getEntityId()).isEqualTo("entity-id"); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getVerificationX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details.getEncryptionX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); } // gh-9051 @Test public void readWhenEntitiesDescriptorThenConfigures() throws Exception { String payload = String.format(ENTITIES_DESCRIPTOR_TEMPLATE, String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"signing\"") + String.format(KEY_DESCRIPTOR_TEMPLATE, "use=\"encryption\"") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE)))); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); RelyingPartyRegistration registration = this.converter.read(RelyingPartyRegistration.Builder.class, response) .registrationId("one").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getWantAuthnRequestsSigned()).isFalse(); assertThat(details.getSingleSignOnServiceLocation()).isEqualTo("sso-location"); assertThat(details.getSingleSignOnServiceBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(details.getEntityId()).isEqualTo("entity-id"); assertThat(details.getVerificationX509Credentials()).hasSize(1); assertThat(details.getVerificationX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details.getEncryptionX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); } @Test public void readWhenKeyDescriptorHasNoUseThenConfiguresBothKeyTypes() throws Exception { String payload = String.format(ENTITY_DESCRIPTOR_TEMPLATE, String.format(IDP_SSO_DESCRIPTOR_TEMPLATE, String.format(KEY_DESCRIPTOR_TEMPLATE, "") + String.format(SINGLE_SIGN_ON_SERVICE_TEMPLATE))); MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); RelyingPartyRegistration registration = this.converter.read(RelyingPartyRegistration.Builder.class, response) .registrationId("one").build(); RelyingPartyRegistration.AssertingPartyDetails details = registration.getAssertingPartyDetails(); assertThat(details.getVerificationX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); assertThat(details.getEncryptionX509Credentials()).hasSize(1); assertThat(details.getEncryptionX509Credentials().iterator().next().getCertificate()) .isEqualTo(x509Certificate(CERTIFICATE)); } X509Certificate x509Certificate(String data) { try { InputStream certificate = new ByteArrayInputStream(Base64.getDecoder().decode(data.getBytes())); return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certificate); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } // gh-9051 @Test public void readWhenUnsupportedElementThenSaml2Exception() { String payload = "<saml2:Assertion xmlns:saml2=\"https://some.endpoint\"/>"; MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> this.converter.read(RelyingPartyRegistration.Builder.class, response)) .withMessage("Unsupported element of type saml2:Assertion"); } }
10,507
58.033708
1,442
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationTests.java
/* * 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.registration; import org.junit.jupiter.api.Test; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.web.authentication.Saml2WebSsoAuthenticationFilter; import static org.assertj.core.api.Assertions.assertThat; public class RelyingPartyRegistrationTests { @Test public void withRelyingPartyRegistrationWorks() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .nameIdFormat("format").authnRequestsSigned(true) .assertingPartyDetails((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyDetails((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyDetails((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); RelyingPartyRegistration copy = RelyingPartyRegistration.withRelyingPartyRegistration(registration).build(); compareRegistrations(registration, copy); } @Test void mutateWhenInvokedThenCreatesCopy() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .nameIdFormat("format") .assertingPartyDetails((a) -> a.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .assertingPartyDetails((a) -> a.wantAuthnRequestsSigned(false)) .assertingPartyDetails((a) -> a.signingAlgorithms((algs) -> algs.add("alg"))) .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); RelyingPartyRegistration copy = registration.mutate().build(); compareRegistrations(registration, copy); } private void compareRegistrations(RelyingPartyRegistration registration, RelyingPartyRegistration copy) { assertThat(copy.getRegistrationId()).isEqualTo(registration.getRegistrationId()).isEqualTo("simplesamlphp"); assertThat(copy.getAssertingPartyDetails().getEntityId()) .isEqualTo(registration.getAssertingPartyDetails().getEntityId()) .isEqualTo("https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php"); assertThat(copy.getAssertionConsumerServiceLocation()) .isEqualTo(registration.getAssertionConsumerServiceLocation()) .isEqualTo("{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI); assertThat(copy.getSigningX509Credentials()).containsAll(registration.getSigningX509Credentials()); assertThat(copy.getDecryptionX509Credentials()).containsAll(registration.getDecryptionX509Credentials()); assertThat(copy.getEntityId()).isEqualTo(registration.getEntityId()).isEqualTo(copy.getEntityId()) .isEqualTo(registration.getEntityId()) .isEqualTo("{baseUrl}/saml2/service-provider-metadata/{registrationId}"); assertThat(copy.getAssertingPartyDetails().getSingleSignOnServiceLocation()) .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()) .isEqualTo("https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php"); assertThat(copy.getAssertingPartyDetails().getSingleSignOnServiceBinding()) .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) .isEqualTo(Saml2MessageBinding.POST); assertThat(copy.getAssertingPartyDetails().getWantAuthnRequestsSigned()) .isEqualTo(registration.getAssertingPartyDetails().getWantAuthnRequestsSigned()).isFalse(); assertThat(copy.getAssertionConsumerServiceBinding()) .isEqualTo(registration.getAssertionConsumerServiceBinding()); assertThat(copy.getDecryptionX509Credentials()).isEqualTo(registration.getDecryptionX509Credentials()); assertThat(copy.getSigningX509Credentials()).isEqualTo(registration.getSigningX509Credentials()); assertThat(copy.getAssertingPartyDetails().getEncryptionX509Credentials()) .isEqualTo(registration.getAssertingPartyDetails().getEncryptionX509Credentials()); assertThat(copy.getAssertingPartyDetails().getVerificationX509Credentials()) .isEqualTo(registration.getAssertingPartyDetails().getVerificationX509Credentials()); assertThat(copy.getAssertingPartyDetails().getSigningAlgorithms()) .isEqualTo(registration.getAssertingPartyDetails().getSigningAlgorithms()); assertThat(copy.getNameIdFormat()).isEqualTo(registration.getNameIdFormat()); assertThat(copy.isAuthnRequestsSigned()).isEqualTo(registration.isAuthnRequestsSigned()); } @Test public void buildWhenUsingDefaultsThenAssertionConsumerServiceBindingDefaultsToPost() { RelyingPartyRegistration relyingPartyRegistration = RelyingPartyRegistration.withRegistrationId("id") .entityId("entity-id").assertionConsumerServiceLocation("location") .assertingPartyDetails((assertingParty) -> assertingParty.entityId("entity-id") .singleSignOnServiceLocation("location").verificationX509Credentials( (c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); assertThat(relyingPartyRegistration.getAssertionConsumerServiceBinding()).isEqualTo(Saml2MessageBinding.POST); } @Test public void buildPreservesCredentialsOrder() { Saml2X509Credential altRpCredential = TestSaml2X509Credentials.altPrivateCredential(); Saml2X509Credential altApCredential = TestSaml2X509Credentials.altPublicCredential(); Saml2X509Credential verifyingCredential = TestSaml2X509Credentials.relyingPartyVerifyingCredential(); Saml2X509Credential encryptingCredential = TestSaml2X509Credentials.relyingPartyEncryptingCredential(); Saml2X509Credential signingCredential = TestSaml2X509Credentials.relyingPartySigningCredential(); Saml2X509Credential decryptionCredential = TestSaml2X509Credentials.relyingPartyDecryptingCredential(); // Test with the alt credentials first RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyDetails((assertingParty) -> assertingParty.verificationX509Credentials((c) -> { c.add(altApCredential); c.add(verifyingCredential); }).encryptionX509Credentials((c) -> { c.add(altApCredential); c.add(encryptingCredential); })).signingX509Credentials((c) -> { c.add(altRpCredential); c.add(signingCredential); }).decryptionX509Credentials((c) -> { c.add(altRpCredential); c.add(decryptionCredential); }).build(); assertThat(relyingPartyRegistration.getSigningX509Credentials()).containsExactly(altRpCredential, signingCredential); assertThat(relyingPartyRegistration.getDecryptionX509Credentials()).containsExactly(altRpCredential, decryptionCredential); assertThat(relyingPartyRegistration.getAssertingPartyDetails().getVerificationX509Credentials()) .containsExactly(altApCredential, verifyingCredential); assertThat(relyingPartyRegistration.getAssertingPartyDetails().getEncryptionX509Credentials()) .containsExactly(altApCredential, encryptingCredential); // Test with the alt credentials last relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyDetails((assertingParty) -> assertingParty.verificationX509Credentials((c) -> { c.add(verifyingCredential); c.add(altApCredential); }).encryptionX509Credentials((c) -> { c.add(encryptingCredential); c.add(altApCredential); })).signingX509Credentials((c) -> { c.add(signingCredential); c.add(altRpCredential); }).decryptionX509Credentials((c) -> { c.add(decryptionCredential); c.add(altRpCredential); }).build(); assertThat(relyingPartyRegistration.getSigningX509Credentials()).containsExactly(signingCredential, altRpCredential); assertThat(relyingPartyRegistration.getDecryptionX509Credentials()).containsExactly(decryptionCredential, altRpCredential); assertThat(relyingPartyRegistration.getAssertingPartyDetails().getVerificationX509Credentials()) .containsExactly(verifyingCredential, altApCredential); assertThat(relyingPartyRegistration.getAssertingPartyDetails().getEncryptionX509Credentials()) .containsExactly(encryptingCredential, altApCredential); } }
8,775
54.544304
112
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/registration/TestRelyingPartyRegistrations.java
/* * 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.registration; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.web.authentication.Saml2WebSsoAuthenticationFilter; /** * Preconfigured test data for {@link RelyingPartyRegistration} objects */ public final class TestRelyingPartyRegistrations { private TestRelyingPartyRegistrations() { } public static RelyingPartyRegistration.Builder relyingPartyRegistration() { String registrationId = "simplesamlphp"; String rpEntityId = "{baseUrl}/saml2/service-provider-metadata/{registrationId}"; Saml2X509Credential signingCredential = TestSaml2X509Credentials.relyingPartySigningCredential(); String assertionConsumerServiceLocation = "{baseUrl}" + Saml2WebSsoAuthenticationFilter.DEFAULT_FILTER_PROCESSES_URI; String apEntityId = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php"; Saml2X509Credential verificationCertificate = TestSaml2X509Credentials.relyingPartyVerifyingCredential(); String singleSignOnServiceLocation = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php"; String singleLogoutServiceLocation = "{baseUrl}/logout/saml2/slo"; return RelyingPartyRegistration.withRegistrationId(registrationId).entityId(rpEntityId).nameIdFormat("format") .assertionConsumerServiceLocation(assertionConsumerServiceLocation) .singleLogoutServiceLocation(singleLogoutServiceLocation) .signingX509Credentials((c) -> c.add(signingCredential)).assertingPartyDetails( (a) -> a.entityId(apEntityId).singleSignOnServiceLocation(singleSignOnServiceLocation) .verificationX509Credentials((c) -> c.add(verificationCertificate))); } public static RelyingPartyRegistration.Builder noCredentials() { return RelyingPartyRegistration.withRegistrationId("registration-id").entityId("rp-entity-id") .singleLogoutServiceLocation("https://rp.example.org/logout/saml2/request") .singleLogoutServiceResponseLocation("https://rp.example.org/logout/saml2/response") .assertionConsumerServiceLocation("https://rp.example.org/acs") .assertingPartyDetails((party) -> party.entityId("ap-entity-id") .singleSignOnServiceLocation("https://ap.example.org/sso") .singleLogoutServiceLocation("https://ap.example.org/logout/saml2/request") .singleLogoutServiceResponseLocation("https://ap.example.org/logout/saml2/response")); } public static RelyingPartyRegistration.Builder full() { return noCredentials() .signingX509Credentials((c) -> c.add(org.springframework.security.saml2.core.TestSaml2X509Credentials .relyingPartySigningCredential())) .decryptionX509Credentials((c) -> c.add(org.springframework.security.saml2.core.TestSaml2X509Credentials .relyingPartyDecryptingCredential())) .assertingPartyDetails((party) -> party.verificationX509Credentials( (c) -> c.add(org.springframework.security.saml2.core.TestSaml2X509Credentials .relyingPartyVerifyingCredential()))); } }
3,768
51.347222
116
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolverTests.java
/* * 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.provider.service.web; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; 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.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link DefaultRelyingPartyRegistrationResolver} */ public class DefaultRelyingPartyRegistrationResolverTests { private final RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .build(); private final RelyingPartyRegistrationRepository repository = new InMemoryRelyingPartyRegistrationRepository( this.registration); private final DefaultRelyingPartyRegistrationResolver resolver = new DefaultRelyingPartyRegistrationResolver( this.repository); @Test public void resolveWhenRequestContainsRegistrationIdThenResolves() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/some/path/" + this.registration.getRegistrationId()); RelyingPartyRegistration registration = this.resolver.convert(request); assertThat(registration).isNotNull(); assertThat(registration.getRegistrationId()).isEqualTo(this.registration.getRegistrationId()); assertThat(registration.getEntityId()) .isEqualTo("http://localhost/saml2/service-provider-metadata/" + this.registration.getRegistrationId()); assertThat(registration.getAssertionConsumerServiceLocation()) .isEqualTo("http://localhost/login/saml2/sso/" + this.registration.getRegistrationId()); assertThat(registration.getSingleLogoutServiceLocation()).isEqualTo("http://localhost/logout/saml2/slo"); assertThat(registration.getSingleLogoutServiceResponseLocation()) .isEqualTo("http://localhost/logout/saml2/slo"); } @Test public void resolveWhenRequestContainsInvalidRegistrationIdThenNull() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/some/path/not-" + this.registration.getRegistrationId()); RelyingPartyRegistration registration = this.resolver.convert(request); assertThat(registration).isNull(); } @Test public void resolveWhenRequestIsMissingRegistrationIdThenNull() { MockHttpServletRequest request = new MockHttpServletRequest(); RelyingPartyRegistration registration = this.resolver.convert(request); assertThat(registration).isNull(); } @Test public void constructorWhenNullRelyingPartyRegistrationThenIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultRelyingPartyRegistrationResolver(null)); } }
3,645
44.012346
115
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationPlaceholderResolversTests.java
/* * 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 org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link RelyingPartyRegistrationPlaceholderResolvers} */ public class RelyingPartyRegistrationPlaceholderResolversTests { @Test void uriResolverGivenRequestCreatesResolver() { MockHttpServletRequest request = new MockHttpServletRequest(); UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request); String resolved = uriResolver.resolve("{baseUrl}/extension"); assertThat(resolved).isEqualTo("http://localhost/extension"); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> uriResolver.resolve("{baseUrl}/extension/{registrationId}")); } @Test void uriResolverGivenRequestAndRegistrationCreatesResolver() { MockHttpServletRequest request = new MockHttpServletRequest(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .entityId("http://sp.example.org").build(); UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String resolved = uriResolver.resolve("{baseUrl}/extension/{registrationId}"); assertThat(resolved).isEqualTo("http://localhost/extension/simplesamlphp"); resolved = uriResolver.resolve("{relyingPartyEntityId}/extension"); assertThat(resolved).isEqualTo("http://sp.example.org/extension"); } }
2,568
44.070175
120
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilterTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import jakarta.servlet.FilterChain; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.metadata.Saml2MetadataResolver; 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.security.web.util.matcher.AntPathRequestMatcher; 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; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Tests for {@link Saml2MetadataFilter} */ public class Saml2MetadataFilterTests { RelyingPartyRegistrationRepository repository; Saml2MetadataResolver resolver; Saml2MetadataFilter filter; MockHttpServletRequest request; MockHttpServletResponse response; FilterChain chain; @BeforeEach public void setup() { this.repository = mock(RelyingPartyRegistrationRepository.class); this.resolver = mock(Saml2MetadataResolver.class); this.filter = new Saml2MetadataFilter(this.repository, this.resolver); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.chain = mock(FilterChain.class); } @Test public void doFilterWhenMatcherSucceedsThenResolverInvoked() throws Exception { this.request.setPathInfo("/saml2/service-provider-metadata/registration-id"); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.chain); verify(this.repository).findByRegistrationId("registration-id"); } @Test public void doFilterWhenMatcherFailsThenProcessesFilterChain() throws Exception { this.request.setPathInfo("/saml2/authenticate/registration-id"); this.filter.doFilter(this.request, this.response, this.chain); verify(this.chain).doFilter(this.request, this.response); } @Test public void doFilterWhenNoRelyingPartyRegistrationThenUnauthorized() throws Exception { this.request.setPathInfo("/saml2/service-provider-metadata/invalidRegistration"); given(this.repository.findByRegistrationId("invalidRegistration")).willReturn(null); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.chain); assertThat(this.response.getStatus()).isEqualTo(401); } @Test public void doFilterWhenRelyingPartyRegistrationFoundThenInvokesMetadataResolver() throws Exception { this.request.setPathInfo("/saml2/service-provider-metadata/validRegistration"); RelyingPartyRegistration validRegistration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyDetails((party) -> party.verificationX509Credentials( (c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); String generatedMetadata = "<xml>test</xml>"; given(this.resolver.resolve(validRegistration)).willReturn(generatedMetadata); this.filter = new Saml2MetadataFilter((request, registrationId) -> validRegistration, this.resolver); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.chain); assertThat(this.response.getStatus()).isEqualTo(200); assertThat(this.response.getContentAsString()).isEqualTo(generatedMetadata); verify(this.resolver).resolve(validRegistration); } @Test public void doFilterWhenCustomRequestMatcherThenUses() throws Exception { this.request.setPathInfo("/path"); this.filter.setRequestMatcher(new AntPathRequestMatcher("/path")); this.filter.doFilter(this.request, this.response, this.chain); verifyNoInteractions(this.chain); verify(this.repository).findByRegistrationId("path"); } @Test public void doFilterWhenSetMetadataFilenameThenUses() throws Exception { RelyingPartyRegistration validRegistration = TestRelyingPartyRegistrations.full().build(); String testMetadataFilename = "test-{registrationId}-metadata.xml"; String fileName = testMetadataFilename.replace("{registrationId}", validRegistration.getRegistrationId()); String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); String generatedMetadata = "<xml>test</xml>"; this.request.setPathInfo("/saml2/service-provider-metadata/registration-id"); given(this.resolver.resolve(validRegistration)).willReturn(generatedMetadata); this.filter = new Saml2MetadataFilter((request, registrationId) -> validRegistration, this.resolver); this.filter.setMetadataFilename(testMetadataFilename); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.response.getHeaderValue(HttpHeaders.CONTENT_DISPOSITION)).asString() .isEqualTo("attachment; filename=\"%s\"; filename*=UTF-8''%s", fileName, encodedFileName); } @Test public void doFilterWhenResolverConstructorAndPathStartsWithRegistrationIdThenServesMetadata() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); given(this.repository.findByRegistrationId("registration-id")).willReturn(registration); given(this.resolver.resolve(any(RelyingPartyRegistration.class))).willReturn("metadata"); RelyingPartyRegistrationResolver resolver = new DefaultRelyingPartyRegistrationResolver( (id) -> this.repository.findByRegistrationId("registration-id")); this.filter = new Saml2MetadataFilter(resolver, this.resolver); this.filter.setRequestMatcher(new AntPathRequestMatcher("/metadata")); this.request.setPathInfo("/metadata"); this.filter.doFilter(this.request, this.response, new MockFilterChain()); verify(this.repository).findByRegistrationId("registration-id"); } @Test public void doFilterWhenRelyingPartyRegistrationRepositoryConstructorAndPathStartsWithRegistrationIdThenServesMetadata() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); given(this.repository.findByRegistrationId("registration-id")).willReturn(registration); given(this.resolver.resolve(any(RelyingPartyRegistration.class))).willReturn("metadata"); this.filter = new Saml2MetadataFilter((id) -> this.repository.findByRegistrationId("registration-id"), this.resolver); this.filter.setRequestMatcher(new AntPathRequestMatcher("/metadata")); this.request.setPathInfo("/metadata"); this.filter.doFilter(this.request, this.response, new MockFilterChain()); verify(this.repository).findByRegistrationId("registration-id"); } // gh-12026 @Test public void doFilterWhenCharacterEncodingThenEncodeSpecialCharactersCorrectly() throws Exception { RelyingPartyRegistration validRegistration = TestRelyingPartyRegistrations.full().build(); String testMetadataFilename = "test-{registrationId}-metadata.xml"; String generatedMetadata = "<xml>testäöü</xml>"; this.request.setPathInfo("/saml2/service-provider-metadata/registration-id"); given(this.resolver.resolve(validRegistration)).willReturn(generatedMetadata); this.filter = new Saml2MetadataFilter((req, id) -> validRegistration, this.resolver); this.filter.setMetadataFilename(testMetadataFilename); this.filter.doFilter(this.request, this.response, this.chain); assertThat(this.response.getCharacterEncoding()).isEqualTo(StandardCharsets.UTF_8.name()); assertThat(this.response.getContentAsString(StandardCharsets.UTF_8)).isEqualTo(generatedMetadata); } @Test public void setRequestMatcherWhenNullThenIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setRequestMatcher(null)); } @Test public void setMetadataFilenameWhenEmptyThenThrowsException() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.filter.setMetadataFilename(" ")) .withMessage("metadataFilename cannot be empty"); } @Test public void setMetadataFilenameWhenMissingRegistrationIdVariableThenThrowsException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.filter.setMetadataFilename("metadata-filename.xml")) .withMessage("metadataFilename must contain a {registrationId} match variable"); } @Test public void constructorWhenRelyingPartyRegistrationRepositoryThenUses() throws Exception { RelyingPartyRegistrationRepository repository = mock(RelyingPartyRegistrationRepository.class); this.filter = new Saml2MetadataFilter(repository, this.resolver); this.request.setPathInfo("/saml2/service-provider-metadata/one"); this.filter.doFilter(this.request, this.response, this.chain); verify(repository).findByRegistrationId("one"); } }
9,975
46.504762
121
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2WebSsoAuthenticationRequestFilterTests.java
/* * 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 jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.saml2.credentials.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver; import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.UriUtils; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class Saml2WebSsoAuthenticationRequestFilterTests { private static final String IDP_SSO_URL = "https://sso-url.example.com/IDP/SSO"; private Saml2WebSsoAuthenticationRequestFilter filter; private RelyingPartyRegistrationRepository repository = mock(RelyingPartyRegistrationRepository.class); private Saml2AuthenticationRequestResolver authenticationRequestResolver = mock( Saml2AuthenticationRequestResolver.class); private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock( Saml2AuthenticationRequestRepository.class); private MockHttpServletRequest request; private MockHttpServletResponse response; private MockFilterChain filterChain; private RelyingPartyRegistration.Builder rpBuilder; @BeforeEach public void setup() { this.filter = new Saml2WebSsoAuthenticationRequestFilter(this.authenticationRequestResolver); this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.request.setPathInfo("/saml2/authenticate/registration-id"); this.filterChain = new MockFilterChain() { @Override public void doFilter(ServletRequest request, ServletResponse response) { ((HttpServletResponse) response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } }; this.rpBuilder = RelyingPartyRegistration.withRegistrationId("registration-id") .assertingPartyDetails((c) -> c.entityId("idp-entity-id")) .assertingPartyDetails((c) -> c.singleSignOnServiceLocation(IDP_SSO_URL)) .assertionConsumerServiceLocation("template") .signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential())) .decryptionX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential())); this.filter.setAuthenticationRequestRepository(this.authenticationRequestRepository); } @Test public void doFilterWhenNoRelayStateThenRedirectDoesNotContainParameter() throws ServletException, IOException { Saml2RedirectAuthenticationRequest request = redirectAuthenticationRequest().build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).doesNotContain("RelayState=").startsWith(IDP_SSO_URL); } private static Saml2RedirectAuthenticationRequest.Builder redirectAuthenticationRequest() { return Saml2RedirectAuthenticationRequest .withRelyingPartyRegistration(TestRelyingPartyRegistrations.relyingPartyRegistration().build()) .samlRequest("request").authenticationRequestUri(IDP_SSO_URL); } private static Saml2RedirectAuthenticationRequest.Builder redirectAuthenticationRequest( RelyingPartyRegistration registration) { return Saml2RedirectAuthenticationRequest.withRelyingPartyRegistration(registration).samlRequest("request") .authenticationRequestUri(IDP_SSO_URL); } private static Saml2PostAuthenticationRequest.Builder postAuthenticationRequest() { return Saml2PostAuthenticationRequest .withRelyingPartyRegistration(TestRelyingPartyRegistrations.relyingPartyRegistration().build()) .samlRequest("request").authenticationRequestUri(IDP_SSO_URL); } @Test public void doFilterWhenRelayStateThenRedirectDoesContainParameter() throws ServletException, IOException { Saml2RedirectAuthenticationRequest request = redirectAuthenticationRequest().relayState("relayState").build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).contains("RelayState=relayState").startsWith(IDP_SSO_URL); } @Test public void doFilterWhenRelayStateThatRequiresEncodingThenRedirectDoesContainsEncodedParameter() throws Exception { String relayStateValue = "https://my-relay-state.example.com?with=param&other=param"; String relayStateEncoded = UriUtils.encode(relayStateValue, StandardCharsets.ISO_8859_1); Saml2RedirectAuthenticationRequest request = redirectAuthenticationRequest().relayState(relayStateValue) .build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).contains("RelayState=" + relayStateEncoded) .startsWith(IDP_SSO_URL); } @Test public void doFilterWhenSimpleSignatureSpecifiedThenSignatureParametersAreInTheRedirectURL() throws Exception { Saml2RedirectAuthenticationRequest request = redirectAuthenticationRequest().sigAlg("sigalg") .signature("signature").build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).contains("SigAlg=").contains("Signature=") .startsWith(IDP_SSO_URL); } @Test public void doFilterWhenSignatureIsDisabledThenSignatureParametersAreNotInTheRedirectURL() throws Exception { Saml2RedirectAuthenticationRequest request = redirectAuthenticationRequest().build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).doesNotContain("SigAlg=").doesNotContain("Signature=") .startsWith(IDP_SSO_URL); } @Test public void doFilterWhenPostFormDataIsPresent() throws Exception { String relayStateValue = "https://my-relay-state.example.com?with=param&other=param&javascript{alert('1');}"; String relayStateEncoded = HtmlUtils.htmlEscape(relayStateValue); RelyingPartyRegistration registration = this.rpBuilder .assertingPartyDetails((asserting) -> asserting.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .build(); Saml2PostAuthenticationRequest request = Saml2PostAuthenticationRequest .withRelyingPartyRegistration(registration).samlRequest("request").relayState(relayStateValue).build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); assertThat(this.response.getHeader("Location")).isNull(); assertThat(this.response.getContentAsString()).contains( "<meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">") .contains("<script>window.onload = function() { document.forms[0].submit(); }</script>") .contains("<form action=\"https://sso-url.example.com/IDP/SSO\" method=\"post\">") .contains("<input type=\"hidden\" name=\"SAMLRequest\"") .contains("value=\"" + relayStateEncoded + "\""); } @Test public void doFilterWhenRelyingPartyRegistrationNotFoundThenUnauthorized() throws Exception { Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter( this.authenticationRequestResolver); filter.doFilter(this.request, this.response, this.filterChain); assertThat(this.response.getStatus()).isEqualTo(401); } @Test public void setAuthenticationRequestRepositoryWhenNullThenException() { Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter( this.authenticationRequestResolver); assertThatIllegalArgumentException().isThrownBy(() -> filter.setAuthenticationRequestRepository(null)); } @Test public void doFilterWhenRedirectThenSaveRedirectRequest() throws ServletException, IOException { Saml2RedirectAuthenticationRequest request = redirectAuthenticationRequest().build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); verify(this.authenticationRequestRepository).saveAuthenticationRequest( any(Saml2RedirectAuthenticationRequest.class), eq(this.request), eq(this.response)); } @Test public void doFilterWhenPostThenSaveRedirectRequest() throws ServletException, IOException { RelyingPartyRegistration registration = this.rpBuilder .assertingPartyDetails((asserting) -> asserting.singleSignOnServiceBinding(Saml2MessageBinding.POST)) .build(); Saml2PostAuthenticationRequest request = Saml2PostAuthenticationRequest .withRelyingPartyRegistration(registration).samlRequest("request").build(); given(this.authenticationRequestResolver.resolve(any())).willReturn(request); this.filter.doFilterInternal(this.request, this.response, this.filterChain); verify(this.authenticationRequestRepository).saveAuthenticationRequest( any(Saml2PostAuthenticationRequest.class), eq(this.request), eq(this.response)); } @Test public void doFilterWhenCustomAuthenticationRequestResolverThenUses() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); Saml2RedirectAuthenticationRequest authenticationRequest = redirectAuthenticationRequest(registration).build(); Saml2WebSsoAuthenticationRequestFilter filter = new Saml2WebSsoAuthenticationRequestFilter( this.authenticationRequestResolver); given(this.authenticationRequestResolver.resolve(any())).willReturn(authenticationRequest); filter.doFilterInternal(this.request, this.response, this.filterChain); verify(this.authenticationRequestResolver).resolve(any()); } }
12,040
51.580786
129
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverterTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; import java.io.IOException; import java.nio.charset.StandardCharsets; 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.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.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.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.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public class Saml2AuthenticationTokenConverterTests { @Mock RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.relyingPartyRegistration() .build(); @Test public void convertWhenSamlResponseThenToken() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); 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.relyingPartyRegistration.getRegistrationId()); } @Test public void convertWhenSamlResponseWithRelyingPartyRegistrationResolver( @Mock RelyingPartyRegistrationResolver resolver) { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(resolver); given(resolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); 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.relyingPartyRegistration.getRegistrationId()); verify(resolver).resolve(any(), isNull()); } @Test public void convertWhenSamlResponseInvalidBase64ThenSaml2AuthenticationException() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); 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() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(converter.convert(request)).isNull(); } @Test public void convertWhenNoRelyingPartyRegistrationThenNull() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())).willReturn(null); MockHttpServletRequest request = new MockHttpServletRequest(); assertThat(converter.convert(request)).isNull(); } @Test public void convertWhenGetRequestThenInflates() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); 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.relyingPartyRegistration.getRegistrationId()); } @Test public void convertWhenGetRequestInvalidDeflatedThenSaml2AuthenticationException() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); byte[] invalidDeflated = "invalid".getBytes(); String encoded = Saml2Utils.samlEncode(invalidDeflated); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, encoded); assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> converter.convert(request)) .withCauseInstanceOf(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 { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); MockHttpServletRequest request = new MockHttpServletRequest(); 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.relyingPartyRegistration.getRegistrationId()); Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); converter.setAuthenticationRequestRepository(authenticationRequestRepository); given(this.relyingPartyRegistrationResolver.resolve(any(HttpServletRequest.class), any())) .willReturn(this.relyingPartyRegistration); given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))) .willReturn(authenticationRequest); MockHttpServletRequest request = new MockHttpServletRequest(); 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.relyingPartyRegistration.getRegistrationId()); assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest); } @Test public void convertWhenSavedAuthenticationRequestThenTokenWithRelyingPartyRegistrationResolver( @Mock RelyingPartyRegistrationResolver resolver) { Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock( Saml2AuthenticationRequestRepository.class); AbstractSaml2AuthenticationRequest authenticationRequest = mock(AbstractSaml2AuthenticationRequest.class); given(authenticationRequest.getRelyingPartyRegistrationId()) .willReturn(this.relyingPartyRegistration.getRegistrationId()); Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter(resolver); converter.setAuthenticationRequestRepository(authenticationRequestRepository); given(resolver.resolve(any(HttpServletRequest.class), any())).willReturn(this.relyingPartyRegistration); given(authenticationRequestRepository.loadAuthenticationRequest(any(HttpServletRequest.class))) .willReturn(authenticationRequest); MockHttpServletRequest request = new MockHttpServletRequest(); 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.relyingPartyRegistration.getRegistrationId()); assertThat(token.getAuthenticationRequest()).isEqualTo(authenticationRequest); verify(resolver).resolve(any(), eq(this.relyingPartyRegistration.getRegistrationId())); } @Test public void constructorWhenResolverIsNullThenIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> new Saml2AuthenticationTokenConverter(null)); } @Test public void setAuthenticationRequestRepositoryWhenNullThenIllegalArgument() { Saml2AuthenticationTokenConverter converter = new Saml2AuthenticationTokenConverter( this.relyingPartyRegistrationResolver); 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); } }
12,870
51.109312
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/OpenSamlAuthenticationTokenConverterTests.java
/* * 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 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; 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 OpenSamlAuthenticationTokenConverter} */ @ExtendWith(MockitoExtension.class) public final class OpenSamlAuthenticationTokenConverterTests { @Mock RelyingPartyRegistrationRepository registrations; RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); @Test public void convertWhenSamlResponseThenToken() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations); MockHttpServletRequest request = post("/login/saml2/sso/" + this.registration.getRegistrationId()); assertThat(converter.convert(request)).isNull(); } @Test public void convertWhenNoMatchingRequestThenNull() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(this.registrations); MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "ignored"); assertThat(converter.convert(request)).isNull(); } @Test public void convertWhenNoRelyingPartyRegistrationThenNull() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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)) .withCauseInstanceOf(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 { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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()); OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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() { OpenSamlAuthenticationTokenConverter converter = new OpenSamlAuthenticationTokenConverter(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) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } }
13,001
49.200772
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSamlSigningUtilsTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.util.UUID; import javax.xml.namespace.QName; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.SAMLVersion; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.Response; import org.opensaml.xmlsec.signature.Signature; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; /** * Test open SAML signatures */ public class OpenSamlSigningUtilsTests { static { OpenSamlInitializationService.initialize(); } private RelyingPartyRegistration registration; @BeforeEach public void setup() { this.registration = RelyingPartyRegistration.withRegistrationId("saml-idp") .entityId("https://some.idp.example.com/entity-id").signingX509Credentials((c) -> { c.add(TestSaml2X509Credentials.relyingPartySigningCredential()); c.add(TestSaml2X509Credentials.assertingPartySigningCredential()); }).assertingPartyDetails((c) -> c.entityId("https://some.idp.example.com/entity-id") .singleSignOnServiceLocation("https://some.idp.example.com/service-location")) .build(); } @Test public void whenSigningAnObjectThenKeyInfoIsPartOfTheSignature() { Response response = response("destination", "issuer"); OpenSamlSigningUtils.sign(response, this.registration); Signature signature = response.getSignature(); assertThat(signature).isNotNull(); assertThat(signature.getKeyInfo()).isNotNull(); } Response response(String destination, String issuerEntityId) { Response response = build(Response.DEFAULT_ELEMENT_NAME); response.setID("R" + UUID.randomUUID()); response.setVersion(SAMLVersion.VERSION_20); response.setID("_" + UUID.randomUUID()); response.setDestination(destination); response.setIssuer(issuer(issuerEntityId)); return response; } Issuer issuer(String entityId) { Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(entityId); return issuer; } <T extends XMLObject> T build(QName qName) { return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); } }
3,156
34.077778
103
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/Saml2WebSsoAuthenticationFilterTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.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.TestSaml2AuthenticationTokens; 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.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository; import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationTokenConverter; import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import static org.assertj.core.api.Assertions.assertThatNoException; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; public class Saml2WebSsoAuthenticationFilterTests { private Saml2WebSsoAuthenticationFilter filter; private RelyingPartyRegistrationRepository repository = mock(RelyingPartyRegistrationRepository.class); private MockHttpServletRequest request = new MockHttpServletRequest(); private HttpServletResponse response = new MockHttpServletResponse(); private AuthenticationManager authenticationManager = mock(AuthenticationManager.class); @BeforeEach public void setup() { this.filter = new Saml2WebSsoAuthenticationFilter(this.repository); this.request.setPathInfo("/login/saml2/sso/idp-registration-id"); this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "xml-data-goes-here"); } @Test public void constructingFilterWithMissingRegistrationIdVariableThenThrowsException() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy( () -> this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/url/missing/variable")) .withMessage("filterProcessesUrl must contain a {registrationId} match variable"); } @Test public void constructingFilterWithValidRegistrationIdVariableThenSucceeds() { this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/url/variable/is/present/{registrationId}"); } @Test public void constructingFilterWithMissingRegistrationIdVariableAndCustomAuthenticationConverterThenSucceeds() { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/url/missing/variable"); } @Test public void requiresAuthenticationWhenHappyPathThenReturnsTrue() { Assertions.assertTrue(this.filter.requiresAuthentication(this.request, this.response)); } @Test public void requiresAuthenticationWhenCustomProcessingUrlThenReturnsTrue() { this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}"); this.request.setPathInfo("/some/other/path/idp-registration-id"); this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "xml-data-goes-here"); Assertions.assertTrue(this.filter.requiresAuthentication(this.request, this.response)); } @Test public void attemptAuthenticationWhenRegistrationIdDoesNotExistThenThrowsException() { given(this.repository.findByRegistrationId("non-existent-id")).willReturn(null); this.filter = new Saml2WebSsoAuthenticationFilter(this.repository, "/some/other/path/{registrationId}"); this.request.setPathInfo("/some/other/path/non-existent-id"); this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.filter.attemptAuthentication(this.request, this.response)) .withMessage("No relying party registration found"); } @Test public void attemptAuthenticationWhenSavedAuthnRequestThenRemovesAuthnRequest() { Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock( Saml2AuthenticationRequestRepository.class); AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); given(authenticationConverter.convert(this.request)).willReturn(TestSaml2AuthenticationTokens.token()); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}"); this.filter.setAuthenticationManager((authentication) -> null); this.request.setPathInfo("/some/other/path/idp-registration-id"); this.filter.setAuthenticationRequestRepository(authenticationRequestRepository); this.filter.attemptAuthentication(this.request, this.response); verify(authenticationRequestRepository).removeAuthenticationRequest(this.request, this.response); } @Test public void attemptAuthenticationAddsDetails() { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); final Saml2AuthenticationToken token = TestSaml2AuthenticationTokens.token(); given(authenticationConverter.convert(this.request)).willReturn(token); final AuthenticationDetailsSource authenticationDetailsSource = mock(AuthenticationDetailsSource.class); final WebAuthenticationDetails details = mock(WebAuthenticationDetails.class); given(authenticationDetailsSource.buildDetails(this.request)).willReturn(details); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}"); this.filter.setAuthenticationManager((authentication) -> null); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.request.setPathInfo("/some/other/path/idp-registration-id"); this.filter.attemptAuthentication(this.request, this.response); Assertions.assertEquals(details, token.getDetails()); } @Test public void attemptAuthenticationWhenAuthenticationNotAbstractAuthenticationTokenDoesNotAddDetails() { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); final Authentication authenticationWithoutDetails = mock(Authentication.class); given(authenticationConverter.convert(this.request)).willReturn(authenticationWithoutDetails); final AuthenticationDetailsSource authenticationDetailsSource = mock(AuthenticationDetailsSource.class); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}"); this.filter.setAuthenticationManager((authentication) -> null); this.filter.setAuthenticationDetailsSource(authenticationDetailsSource); this.request.setPathInfo("/some/other/path/idp-registration-id"); assertThatNoException().isThrownBy(() -> this.filter.attemptAuthentication(this.request, this.response)); verifyNoInteractions(authenticationDetailsSource); } @Test public void setAuthenticationRequestRepositoryWhenNullThenThrowsIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.filter.setAuthenticationRequestRepository(null)) .withMessage("authenticationRequestRepository cannot be null"); } @Test public void setAuthenticationRequestRepositoryWhenExpectedAuthenticationConverterTypeThenSetLoaderIntoConverter() { Saml2AuthenticationTokenConverter authenticationConverter = mock(Saml2AuthenticationTokenConverter.class); Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock( Saml2AuthenticationRequestRepository.class); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}"); this.filter.setAuthenticationRequestRepository(authenticationRequestRepository); verify(authenticationConverter).setAuthenticationRequestRepository(authenticationRequestRepository); } @Test public void setAuthenticationRequestRepositoryWhenNotExpectedAuthenticationConverterTypeThenDoNotSet() { AuthenticationConverter authenticationConverter = mock(AuthenticationConverter.class); Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = mock( Saml2AuthenticationRequestRepository.class); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, "/some/other/path/{registrationId}"); this.filter.setAuthenticationRequestRepository(authenticationRequestRepository); verifyNoInteractions(authenticationConverter); } @Test public void doFilterWhenPathStartsWithRegistrationIdThenAuthenticates() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); given(this.repository.findByRegistrationId("registration-id")).willReturn(registration); given(this.authenticationManager.authenticate(authentication)).willReturn(authentication); String loginProcessingUrl = "/{registrationId}/login/saml2/sso"; RequestMatcher matcher = new AntPathRequestMatcher(loginProcessingUrl); DefaultRelyingPartyRegistrationResolver delegate = new DefaultRelyingPartyRegistrationResolver(this.repository); RelyingPartyRegistrationResolver resolver = (request, id) -> { String registrationId = matcher.matcher(request).getVariables().get("registrationId"); return delegate.resolve(request, registrationId); }; Saml2AuthenticationTokenConverter authenticationConverter = new Saml2AuthenticationTokenConverter(resolver); this.filter = new Saml2WebSsoAuthenticationFilter(authenticationConverter, loginProcessingUrl); this.filter.setAuthenticationManager(this.authenticationManager); this.request.setPathInfo("/registration-id/login/saml2/sso"); this.request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); this.filter.doFilter(this.request, this.response, new MockFilterChain()); verify(this.repository).findByRegistrationId("registration-id"); } }
12,115
56.695238
116
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSaml4AuthenticationRequestResolverTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class OpenSaml4AuthenticationRequestResolverTests { MockHttpServletRequest request; RelyingPartyRegistration registration; @BeforeEach void setup() { this.request = givenRequest("/saml2/authenticate/registration-id"); this.registration = TestRelyingPartyRegistrations.full().build(); } @Test void resolveWhenRedirectThenSaml2RedirectAuthenticationRequest() { RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class); given(relyingParties.resolve(any(), any())).willReturn(this.registration); OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties); Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request); assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(authnRequest.getAuthenticationRequestUri()) .isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); } @Test void resolveWhenPostThenSaml2PostAuthenticationRequest() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .assertingPartyDetails((party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST)).build(); RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class); given(relyingParties.resolve(any(), any())).willReturn(registration); OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties); Saml2PostAuthenticationRequest authnRequest = resolver.resolve(this.request); assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(authnRequest.getAuthenticationRequestUri()) .isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); } @Test void resolveWhenCustomRelayStateThenUses() { RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class); given(relyingParties.resolve(any(), any())).willReturn(this.registration); Converter<HttpServletRequest, String> relayState = mock(Converter.class); given(relayState.convert(any())).willReturn("state"); OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties); resolver.setRelayStateResolver(relayState); Saml2RedirectAuthenticationRequest authnRequest = resolver.resolve(this.request); assertThat(authnRequest.getRelayState()).isEqualTo("state"); verify(relayState).convert(any()); } @Test void resolveWhenCustomAuthenticationUrlTHenUses() { RelyingPartyRegistrationResolver relyingParties = mock(RelyingPartyRegistrationResolver.class); given(relyingParties.resolve(any(), any())).willReturn(this.registration); OpenSaml4AuthenticationRequestResolver resolver = new OpenSaml4AuthenticationRequestResolver(relyingParties); resolver.setRequestMatcher(new AntPathRequestMatcher("/custom/authentication/{registrationId}")); Saml2RedirectAuthenticationRequest authnRequest = resolver .resolve(givenRequest("/custom/authentication/registration-id")); assertThat(authnRequest.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(authnRequest.getAuthenticationRequestUri()) .isEqualTo(this.registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); } private MockHttpServletRequest givenRequest(String path) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setServletPath(path); return request; } }
5,408
48.172727
111
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSamlAuthenticationRequestResolverTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link OpenSamlAuthenticationRequestResolver} */ public class OpenSamlAuthenticationRequestResolverTests { private RelyingPartyRegistration.Builder relyingPartyRegistrationBuilder; @BeforeEach public void setUp() { this.relyingPartyRegistrationBuilder = TestRelyingPartyRegistrations.relyingPartyRegistration(); } @ParameterizedTest @MethodSource("provideSignRequestFlags") public void resolveAuthenticationRequestWhenSignedRedirectThenSignsAndRedirects(boolean wantAuthRequestsSigned, boolean authnRequestsSigned) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/saml2/authenticate/registration-id"); RelyingPartyRegistration registration = this.relyingPartyRegistrationBuilder .authnRequestsSigned(authnRequestsSigned) .assertingPartyDetails((party) -> party.wantAuthnRequestsSigned(wantAuthRequestsSigned)).build(); OpenSamlAuthenticationRequestResolver resolver = authenticationRequestResolver(registration); Saml2RedirectAuthenticationRequest result = resolver.resolve(request, (r, authnRequest) -> { UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); assertThat(authnRequest.getNameIDPolicy().getFormat()).isEqualTo(registration.getNameIdFormat()); assertThat(authnRequest.getAssertionConsumerServiceURL()) .isEqualTo(uriResolver.resolve(registration.getAssertionConsumerServiceLocation())); assertThat(authnRequest.getProtocolBinding()) .isEqualTo(registration.getAssertionConsumerServiceBinding().getUrn()); assertThat(authnRequest.getDestination()) .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); assertThat(authnRequest.getIssuer().getValue()).isEqualTo(uriResolver.resolve(registration.getEntityId())); }); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isNotNull(); assertThat(result.getSigAlg()).isEqualTo(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); assertThat(result.getSignature()).isNotEmpty(); assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(result.getId()).isNotEmpty(); } @Test public void resolveAuthenticationRequestWhenUnsignedRedirectThenRedirectsAndNoSignature() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/saml2/authenticate/registration-id"); RelyingPartyRegistration registration = this.relyingPartyRegistrationBuilder .assertingPartyDetails((party) -> party.wantAuthnRequestsSigned(false)).build(); OpenSamlAuthenticationRequestResolver resolver = authenticationRequestResolver(registration); Saml2RedirectAuthenticationRequest result = resolver.resolve(request, (r, authnRequest) -> { UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); assertThat(authnRequest.getNameIDPolicy().getFormat()).isEqualTo(registration.getNameIdFormat()); assertThat(authnRequest.getAssertionConsumerServiceURL()) .isEqualTo(uriResolver.resolve(registration.getAssertionConsumerServiceLocation())); assertThat(authnRequest.getProtocolBinding()) .isEqualTo(registration.getAssertionConsumerServiceBinding().getUrn()); assertThat(authnRequest.getDestination()) .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); assertThat(authnRequest.getIssuer().getValue()).isEqualTo(uriResolver.resolve(registration.getEntityId())); }); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isNotNull(); assertThat(result.getSigAlg()).isNull(); assertThat(result.getSignature()).isNull(); assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(result.getId()).isNotEmpty(); } @Test public void resolveAuthenticationRequestWhenSignedThenCredentialIsRequired() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/saml2/authenticate/registration-id"); Saml2X509Credential credential = TestSaml2X509Credentials.relyingPartyVerifyingCredential(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyDetails((party) -> party.verificationX509Credentials((c) -> c.add(credential))).build(); OpenSamlAuthenticationRequestResolver resolver = authenticationRequestResolver(registration); assertThatExceptionOfType(Saml2Exception.class) .isThrownBy(() -> resolver.resolve(request, (r, authnRequest) -> { })); } @Test public void resolveAuthenticationRequestWhenUnsignedPostThenOnlyPosts() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/saml2/authenticate/registration-id"); RelyingPartyRegistration registration = this.relyingPartyRegistrationBuilder.assertingPartyDetails( (party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST).wantAuthnRequestsSigned(false)) .authnRequestsSigned(false).build(); OpenSamlAuthenticationRequestResolver resolver = authenticationRequestResolver(registration); Saml2PostAuthenticationRequest result = resolver.resolve(request, (r, authnRequest) -> { UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); assertThat(authnRequest.getNameIDPolicy().getFormat()).isEqualTo(registration.getNameIdFormat()); assertThat(authnRequest.getAssertionConsumerServiceURL()) .isEqualTo(uriResolver.resolve(registration.getAssertionConsumerServiceLocation())); assertThat(authnRequest.getProtocolBinding()) .isEqualTo(registration.getAssertionConsumerServiceBinding().getUrn()); assertThat(authnRequest.getDestination()) .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); assertThat(authnRequest.getIssuer().getValue()).isEqualTo(uriResolver.resolve(registration.getEntityId())); }); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isNotNull(); assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(new String(Saml2Utils.samlDecode(result.getSamlRequest()))).doesNotContain("Signature"); assertThat(result.getId()).isNotEmpty(); } @ParameterizedTest @MethodSource("provideSignRequestFlags") public void resolveAuthenticationRequestWhenSignedPostThenSignsAndPosts(boolean wantAuthRequestsSigned, boolean authnRequestsSigned) { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/saml2/authenticate/registration-id"); RelyingPartyRegistration registration = this.relyingPartyRegistrationBuilder .authnRequestsSigned(authnRequestsSigned) .assertingPartyDetails((party) -> party.singleSignOnServiceBinding(Saml2MessageBinding.POST) .wantAuthnRequestsSigned(wantAuthRequestsSigned)) .build(); OpenSamlAuthenticationRequestResolver resolver = authenticationRequestResolver(registration); Saml2PostAuthenticationRequest result = resolver.resolve(request, (r, authnRequest) -> { UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); assertThat(authnRequest.getNameIDPolicy().getFormat()).isEqualTo(registration.getNameIdFormat()); assertThat(authnRequest.getAssertionConsumerServiceURL()) .isEqualTo(uriResolver.resolve(registration.getAssertionConsumerServiceLocation())); assertThat(authnRequest.getProtocolBinding()) .isEqualTo(registration.getAssertionConsumerServiceBinding().getUrn()); assertThat(authnRequest.getDestination()) .isEqualTo(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); assertThat(authnRequest.getIssuer().getValue()).isEqualTo(uriResolver.resolve(registration.getEntityId())); }); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isNotNull(); assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.POST); assertThat(new String(Saml2Utils.samlDecode(result.getSamlRequest()))).contains("Signature"); assertThat(result.getId()).isNotEmpty(); } @Test public void resolveAuthenticationRequestWhenSHA1SignRequestThenSigns() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setPathInfo("/saml2/authenticate/registration-id"); RelyingPartyRegistration registration = this.relyingPartyRegistrationBuilder.assertingPartyDetails( (party) -> party.signingAlgorithms((algs) -> algs.add(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1))) .build(); OpenSamlAuthenticationRequestResolver resolver = authenticationRequestResolver(registration); Saml2RedirectAuthenticationRequest result = resolver.resolve(request, (r, authnRequest) -> { }); assertThat(result.getSamlRequest()).isNotEmpty(); assertThat(result.getRelayState()).isNotNull(); assertThat(result.getSigAlg()).isEqualTo(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); assertThat(result.getSignature()).isNotNull(); assertThat(result.getBinding()).isEqualTo(Saml2MessageBinding.REDIRECT); assertThat(result.getId()).isNotEmpty(); } private OpenSamlAuthenticationRequestResolver authenticationRequestResolver(RelyingPartyRegistration registration) { return new OpenSamlAuthenticationRequestResolver((request, id) -> registration); } private static Stream<Arguments> provideSignRequestFlags() { return Stream.of(Arguments.of(true, true), Arguments.of(true, false), Arguments.of(false, true)); } }
11,680
55.703883
120
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilterTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidator; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; import static org.mockito.BDDMockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Tests for {@link Saml2LogoutResponseFilter} */ public class Saml2LogoutResponseFilterTests { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); Saml2LogoutRequestRepository logoutRequestRepository = mock(Saml2LogoutRequestRepository.class); Saml2LogoutResponseValidator logoutResponseValidator = mock(Saml2LogoutResponseValidator.class); LogoutSuccessHandler logoutSuccessHandler = mock(LogoutSuccessHandler.class); Saml2LogoutResponseFilter logoutResponseProcessingFilter = new Saml2LogoutResponseFilter( this.relyingPartyRegistrationResolver, this.logoutResponseValidator, this.logoutSuccessHandler); @BeforeEach public void setUp() { this.logoutResponseProcessingFilter.setLogoutRequestRepository(this.logoutRequestRepository); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void doFilterWhenSamlResponsePostThenLogout() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); MockHttpServletResponse response = new MockHttpServletResponse(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); given(this.relyingPartyRegistrationResolver.resolve(request, "registration-id")).willReturn(registration); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest("request").build(); given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest); given(this.logoutResponseValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success()); this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verify(this.logoutResponseValidator).validate(any()); verify(this.logoutSuccessHandler).onLogoutSuccess(any(), any(), any()); } @Test public void doFilterWhenSamlResponseRedirectThenLogout() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); MockHttpServletResponse response = new MockHttpServletResponse(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .singleLogoutServiceBinding(Saml2MessageBinding.REDIRECT).build(); given(this.relyingPartyRegistrationResolver.resolve(request, "registration-id")).willReturn(registration); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest("request").build(); given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest); given(this.logoutResponseValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success()); this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verify(this.logoutResponseValidator).validate(any()); verify(this.logoutSuccessHandler).onLogoutSuccess(any(), any(), any()); } @Test public void doFilterWhenRequestMismatchesThenNoLogout() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout"); request.setServletPath("/logout"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); MockHttpServletResponse response = new MockHttpServletResponse(); this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verifyNoInteractions(this.logoutResponseValidator, this.logoutSuccessHandler); } @Test public void doFilterWhenNoSamlRequestOrResponseThenNoLogout() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); MockHttpServletResponse response = new MockHttpServletResponse(); this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verifyNoInteractions(this.logoutResponseValidator, this.logoutSuccessHandler); } @Test public void doFilterWhenValidatorFailsThenStops() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); MockHttpServletResponse response = new MockHttpServletResponse(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); given(this.relyingPartyRegistrationResolver.resolve(request, "registration-id")).willReturn(registration); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest("request").build(); given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest); given(this.logoutResponseValidator.validate(any())) .willReturn(Saml2LogoutValidatorResult.withErrors(new Saml2Error("error", "description")).build()); this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verify(this.logoutResponseValidator).validate(any()); verifyNoInteractions(this.logoutSuccessHandler); } @Test public void doFilterWhenNoRelyingPartyLogoutThen401() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); MockHttpServletResponse response = new MockHttpServletResponse(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null) .singleLogoutServiceResponseLocation(null).build(); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest("request").build(); given(this.logoutRequestRepository.removeLogoutRequest(request, response)).willReturn(logoutRequest); this.logoutResponseProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); assertThat(response.getStatus()).isEqualTo(401); verifyNoInteractions(this.logoutSuccessHandler); } }
9,839
55.228571
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/HttpSessionLogoutRequestRepositoryTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; /** * Tests for {@link HttpSessionLogoutRequestRepository} */ public class HttpSessionLogoutRequestRepositoryTests { HttpSessionLogoutRequestRepository logoutRequestRepository = new HttpSessionLogoutRequestRepository(); @Test public void loadLogoutRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.logoutRequestRepository.loadLogoutRequest(null)); } @Test public void loadLogoutRequestWhenNotSavedThenReturnNull() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(Saml2ParameterNames.RELAY_STATE, "state-1234"); Saml2LogoutRequest logoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(logoutRequest).isNull(); } @Test public void loadLogoutRequestWhenSavedThenReturnLogoutRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, response); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest.getRelayState()); Saml2LogoutRequest loadedLogoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(loadedLogoutRequest).isEqualTo(logoutRequest); } @Test public void loadLogoutRequestWhenMultipleSavedThenReplacesLogoutRequest() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Saml2LogoutRequest one = createLogoutRequest().relayState("state-1122").build(); this.logoutRequestRepository.saveLogoutRequest(one, request, response); Saml2LogoutRequest two = createLogoutRequest().relayState("state-3344").build(); this.logoutRequestRepository.saveLogoutRequest(two, request, response); request.setParameter(Saml2ParameterNames.RELAY_STATE, one.getRelayState()); assertThat(this.logoutRequestRepository.loadLogoutRequest(request)).isNull(); request.setParameter(Saml2ParameterNames.RELAY_STATE, two.getRelayState()); assertThat(this.logoutRequestRepository.loadLogoutRequest(request)).isEqualTo(two); } @Test void serializeAndDeserializeSaml2LogoutRequest() throws IOException, ClassNotFoundException { Saml2LogoutRequest requestToSerialize = createLogoutRequest().relayState("state-serialized").build(); byte[] data; try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream)) { objectOutputStream.writeObject(requestToSerialize); data = outputStream.toByteArray(); } try (ByteArrayInputStream inputStream = new ByteArrayInputStream(data); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream)) { Saml2LogoutRequest deserializedRequest = (Saml2LogoutRequest) objectInputStream.readObject(); assertThat(requestToSerialize.getRelayState()).isEqualTo(deserializedRequest.getRelayState()); } } @Test public void loadLogoutRequestWhenSavedAndStateParameterNullThenReturnNull() { MockHttpServletRequest request = new MockHttpServletRequest(); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, new MockHttpServletResponse()); assertThat(this.logoutRequestRepository.loadLogoutRequest(request)).isNull(); } @Test public void saveLogoutRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() { Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); assertThatIllegalArgumentException().isThrownBy(() -> this.logoutRequestRepository .saveLogoutRequest(logoutRequest, null, new MockHttpServletResponse())); } @Test public void saveLogoutRequestWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() { Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); assertThatIllegalArgumentException().isThrownBy(() -> this.logoutRequestRepository .saveLogoutRequest(logoutRequest, new MockHttpServletRequest(), null)); } @Test public void saveLogoutRequestWhenStateNullThenThrowIllegalArgumentException() { Saml2LogoutRequest logoutRequest = createLogoutRequest().relayState(null).build(); assertThatIllegalArgumentException().isThrownBy(() -> this.logoutRequestRepository .saveLogoutRequest(logoutRequest, new MockHttpServletRequest(), new MockHttpServletResponse())); } @Test public void saveLogoutRequestWhenNotNullThenSaved() { MockHttpServletRequest request = new MockHttpServletRequest(); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, new MockHttpServletResponse()); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest.getRelayState()); Saml2LogoutRequest loadedLogoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(loadedLogoutRequest).isEqualTo(logoutRequest); } @Test public void saveLogoutRequestWhenNoExistingSessionAndDistributedSessionThenSaved() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(new MockDistributedHttpSession()); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, new MockHttpServletResponse()); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest.getRelayState()); Saml2LogoutRequest loadedLogoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(loadedLogoutRequest).isEqualTo(logoutRequest); } @Test public void saveLogoutRequestWhenExistingSessionAndDistributedSessionThenSaved() { MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(new MockDistributedHttpSession()); Saml2LogoutRequest logoutRequest1 = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest1, request, new MockHttpServletResponse()); Saml2LogoutRequest logoutRequest2 = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest2, request, new MockHttpServletResponse()); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest2.getRelayState()); Saml2LogoutRequest loadedLogoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(loadedLogoutRequest).isEqualTo(logoutRequest2); } @Test public void saveLogoutRequestWhenNullThenRemoved() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, response); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest.getRelayState()); this.logoutRequestRepository.saveLogoutRequest(null, request, response); Saml2LogoutRequest loadedLogoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(loadedLogoutRequest).isNull(); } @Test public void removeLogoutRequestWhenHttpServletRequestIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy( () -> this.logoutRequestRepository.removeLogoutRequest(null, new MockHttpServletResponse())); } @Test public void removeLogoutRequestWhenHttpServletResponseIsNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException() .isThrownBy(() -> this.logoutRequestRepository.removeLogoutRequest(new MockHttpServletRequest(), null)); } @Test public void removeLogoutRequestWhenSavedThenRemoved() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, response); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest.getRelayState()); Saml2LogoutRequest removedLogoutRequest = this.logoutRequestRepository.removeLogoutRequest(request, response); Saml2LogoutRequest loadedLogoutRequest = this.logoutRequestRepository.loadLogoutRequest(request); assertThat(removedLogoutRequest).isNotNull(); assertThat(loadedLogoutRequest).isNull(); } // gh-5263 @Test public void removeLogoutRequestWhenSavedThenRemovedFromSession() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Saml2LogoutRequest logoutRequest = createLogoutRequest().build(); this.logoutRequestRepository.saveLogoutRequest(logoutRequest, request, response); request.addParameter(Saml2ParameterNames.RELAY_STATE, logoutRequest.getRelayState()); Saml2LogoutRequest removedLogoutRequest = this.logoutRequestRepository.removeLogoutRequest(request, response); String sessionAttributeName = HttpSessionLogoutRequestRepository.class.getName() + ".AUTHORIZATION_REQUEST"; assertThat(removedLogoutRequest).isNotNull(); assertThat(request.getSession().getAttribute(sessionAttributeName)).isNull(); } @Test public void removeLogoutRequestWhenNotSavedThenNotRemoved() { MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter(Saml2ParameterNames.RELAY_STATE, "state-1234"); MockHttpServletResponse response = new MockHttpServletResponse(); Saml2LogoutRequest removedLogoutRequest = this.logoutRequestRepository.removeLogoutRequest(request, response); assertThat(removedLogoutRequest).isNull(); } private Saml2LogoutRequest.Builder createLogoutRequest() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); return Saml2LogoutRequest.withRelyingPartyRegistration(registration).samlRequest("request").id("id") .parameters((params) -> params.put(Saml2ParameterNames.RELAY_STATE, "state-1234")); } static class MockDistributedHttpSession extends MockHttpSession { @Override public Object getAttribute(String name) { return wrap(super.getAttribute(name)); } @Override public void setAttribute(String name, Object value) { super.setAttribute(name, wrap(value)); } private Object wrap(Object object) { if (object instanceof Map) { object = new HashMap<>((Map<Object, Object>) object); } return object; } } }
12,153
47.039526
112
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolverTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.saml2.core.LogoutRequest; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link OpenSamlLogoutRequestResolver} * * @author Josh Cummings */ public class OpenSamlLogoutRequestResolverTests { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); OpenSamlLogoutRequestResolver logoutRequestResolver = new OpenSamlLogoutRequestResolver( this.relyingPartyRegistrationResolver); @Test public void resolveRedirectWhenAuthenticatedThenIncludesName() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); Saml2Authentication authentication = authentication(registration); HttpServletRequest request = new MockHttpServletRequest(); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutRequest saml2LogoutRequest = this.logoutRequestResolver.resolve(request, authentication); assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIG_ALG)).isNotNull(); assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIGNATURE)).isNotNull(); assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.RELAY_STATE)).isNotNull(); Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); LogoutRequest logoutRequest = getLogoutRequest(saml2LogoutRequest.getSamlRequest(), binding); assertThat(logoutRequest.getNameID().getValue()).isEqualTo(authentication.getName()); } @Test public void resolvePostWhenAuthenticatedThenIncludesName() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)).build(); Saml2Authentication authentication = authentication(registration); HttpServletRequest request = new MockHttpServletRequest(); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutRequest saml2LogoutRequest = this.logoutRequestResolver.resolve(request, authentication); assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIG_ALG)).isNull(); assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.SIGNATURE)).isNull(); assertThat(saml2LogoutRequest.getParameter(Saml2ParameterNames.RELAY_STATE)).isNotNull(); Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); LogoutRequest logoutRequest = getLogoutRequest(saml2LogoutRequest.getSamlRequest(), binding); assertThat(logoutRequest.getNameID().getValue()).isEqualTo(authentication.getName()); assertThat(logoutRequest.getSessionIndexes()).hasSize(1); assertThat(logoutRequest.getSessionIndexes().get(0).getValue()).isEqualTo("session-index"); } private Saml2Authentication authentication(RelyingPartyRegistration registration) { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", new HashMap<>(), Arrays.asList("session-index")); principal.setRelyingPartyRegistrationId(registration.getRegistrationId()); return new Saml2Authentication(principal, "response", new ArrayList<>()); } private LogoutRequest getLogoutRequest(String samlRequest, Saml2MessageBinding binding) { if (binding == Saml2MessageBinding.REDIRECT) { samlRequest = Saml2Utils.samlInflate(Saml2Utils.samlDecode(samlRequest)); } else { samlRequest = new String(Saml2Utils.samlDecode(samlRequest), StandardCharsets.UTF_8); } try { Document document = XMLObjectProviderRegistrySupport.getParserPool() .parse(new ByteArrayInputStream(samlRequest.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutRequest) XMLObjectProviderRegistrySupport.getUnmarshallerFactory().getUnmarshaller(element) .unmarshall(element); } catch (Exception ex) { throw new Saml2Exception(ex); } } }
6,081
49.683333
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutResponseResolverTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.util.function.Consumer; import org.junit.jupiter.api.Test; import org.opensaml.saml.saml2.core.LogoutRequest; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSaml4LogoutResponseResolver.LogoutResponseParameters; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link OpenSaml4LogoutResponseResolver} */ public class OpenSaml4LogoutResponseResolverTests { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); @Test public void resolveWhenCustomParametersConsumerThenUses() { OpenSaml4LogoutResponseResolver logoutResponseResolver = new OpenSaml4LogoutResponseResolver( this.relyingPartyRegistrationResolver); Consumer<LogoutResponseParameters> parametersConsumer = mock(Consumer.class); logoutResponseResolver.setParametersConsumer(parametersConsumer); MockHttpServletRequest request = new MockHttpServletRequest(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration() .assertingPartyDetails( (party) -> party.singleLogoutServiceResponseLocation("https://ap.example.com/logout")) .build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutResponse logoutResponse = logoutResponseResolver.resolve(request, authentication); assertThat(logoutResponse).isNotNull(); verify(parametersConsumer).accept(any()); } @Test public void setParametersConsumerWhenNullThenIllegalArgument() { OpenSaml4LogoutRequestResolver logoutRequestResolver = new OpenSaml4LogoutRequestResolver( this.relyingPartyRegistrationResolver); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> logoutRequestResolver.setParametersConsumer(null)); } }
3,884
48.177215
142
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlSigningUtilsTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.util.UUID; import javax.xml.namespace.QName; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.common.SAMLVersion; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.Response; import org.opensaml.xmlsec.signature.Signature; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; /** * Test open SAML signatures */ public class OpenSamlSigningUtilsTests { static { OpenSamlInitializationService.initialize(); } private RelyingPartyRegistration registration; @BeforeEach public void setup() { this.registration = RelyingPartyRegistration.withRegistrationId("saml-idp") .entityId("https://some.idp.example.com/entity-id").signingX509Credentials((c) -> { c.add(TestSaml2X509Credentials.relyingPartySigningCredential()); c.add(TestSaml2X509Credentials.assertingPartySigningCredential()); }).assertingPartyDetails((c) -> c.entityId("https://some.idp.example.com/entity-id") .singleSignOnServiceLocation("https://some.idp.example.com/service-location")) .build(); } @Test public void whenSigningAnObjectThenKeyInfoIsPartOfTheSignature() { Response response = response("destination", "issuer"); OpenSamlSigningUtils.sign(response, this.registration); Signature signature = response.getSignature(); assertThat(signature).isNotNull(); assertThat(signature.getKeyInfo()).isNotNull(); } Response response(String destination, String issuerEntityId) { Response response = build(Response.DEFAULT_ELEMENT_NAME); response.setID("R" + UUID.randomUUID()); response.setVersion(SAMLVersion.VERSION_20); response.setID("_" + UUID.randomUUID()); response.setDestination(destination); response.setIssuer(issuer(issuerEntityId)); return response; } Issuer issuer(String entityId) { Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(entityId); return issuer; } <T extends XMLObject> T build(QName qName) { return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); } }
3,163
34.155556
103
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSaml4LogoutRequestResolverTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import jakarta.servlet.http.HttpServletRequest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.core.convert.converter.Converter; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link OpenSaml4LogoutRequestResolver} */ public class OpenSaml4LogoutRequestResolverTests { RelyingPartyRegistration registration; RelyingPartyRegistrationResolver registrationResolver; OpenSaml4LogoutRequestResolver logoutRequestResolver; @BeforeEach public void setup() { this.registration = TestRelyingPartyRegistrations.full().build(); this.registrationResolver = mock(RelyingPartyRegistrationResolver.class); this.logoutRequestResolver = new OpenSaml4LogoutRequestResolver(this.registrationResolver); } @Test public void resolveWhenCustomParametersConsumerThenUses() { this.logoutRequestResolver.setParametersConsumer((parameters) -> parameters.getLogoutRequest().setID("myid")); given(this.registrationResolver.resolve(any(), any())).willReturn(this.registration); Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(givenRequest(), givenAuthentication()); assertThat(logoutRequest.getId()).isEqualTo("myid"); } @Test public void setParametersConsumerWhenNullThenIllegalArgument() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> this.logoutRequestResolver.setParametersConsumer(null)); } @Test public void resolveWhenCustomRelayStateThenUses() { given(this.registrationResolver.resolve(any(), any())).willReturn(this.registration); Converter<HttpServletRequest, String> relayState = mock(Converter.class); given(relayState.convert(any())).willReturn("any-state"); this.logoutRequestResolver.setRelayStateResolver(relayState); Saml2LogoutRequest logoutRequest = this.logoutRequestResolver.resolve(givenRequest(), givenAuthentication()); assertThat(logoutRequest.getRelayState()).isEqualTo("any-state"); verify(relayState).convert(any()); } private static Authentication givenAuthentication() { return new TestingAuthenticationToken("user", "password"); } private MockHttpServletRequest givenRequest() { return new MockHttpServletRequest(); } }
3,786
38.863158
112
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolverTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.nio.charset.StandardCharsets; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.Marshaller; import org.opensaml.core.xml.io.MarshallingException; import org.w3c.dom.Element; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; import org.springframework.security.saml2.provider.service.authentication.TestSaml2Authentications; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) public final class OpenSamlLogoutRequestValidatorParametersResolverTests { @Mock RelyingPartyRegistrationRepository registrations; private RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); private OpenSamlLogoutRequestValidatorParametersResolver resolver; @BeforeEach void setup() { this.resolver = new OpenSamlLogoutRequestValidatorParametersResolver(this.registrations); } @Test void saml2LogoutRegistrationIdResolveWhenMatchesThenParameters() { String registrationId = this.registration.getRegistrationId(); MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId); Authentication authentication = new TestingAuthenticationToken("user", "pass"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration); Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication); assertThat(parameters.getAuthentication()).isEqualTo(authentication); assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request"); } @Test void saml2LogoutRegistrationIdWhenUnauthenticatedThenParameters() { String registrationId = this.registration.getRegistrationId(); MockHttpServletRequest request = post("/logout/saml2/slo/" + registrationId); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration); Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null); assertThat(parameters.getAuthentication()).isNull(); assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request"); } @Test void saml2LogoutResolveWhenAuthenticatedThenParameters() { String registrationId = this.registration.getRegistrationId(); MockHttpServletRequest request = post("/logout/saml2/slo"); Authentication authentication = TestSaml2Authentications.authentication(); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); given(this.registrations.findByRegistrationId(registrationId)).willReturn(this.registration); Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, authentication); assertThat(parameters.getAuthentication()).isEqualTo(authentication); assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo("request"); } @Test void saml2LogoutResolveWhenUnauthenticatedThenParameters() { String registrationId = this.registration.getRegistrationId(); MockHttpServletRequest request = post("/logout/saml2/slo"); String logoutRequest = serialize(TestOpenSamlObjects.logoutRequest()); String encoded = Saml2Utils.samlEncode(logoutRequest.getBytes(StandardCharsets.UTF_8)); request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded); given(this.registrations.findUniqueByAssertingPartyEntityId(TestOpenSamlObjects.ASSERTING_PARTY_ENTITY_ID)) .willReturn(this.registration); Saml2LogoutRequestValidatorParameters parameters = this.resolver.resolve(request, null); assertThat(parameters.getAuthentication()).isNull(); assertThat(parameters.getRelyingPartyRegistration().getRegistrationId()).isEqualTo(registrationId); assertThat(parameters.getLogoutRequest().getSamlRequest()).isEqualTo(encoded); } @Test void saml2LogoutRegistrationIdResolveWhenNoMatchingRegistrationIdThenSaml2Exception() { MockHttpServletRequest request = post("/logout/saml2/slo/id"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.resolver.resolve(request, null)); } private MockHttpServletRequest post(String uri) { MockHttpServletRequest request = new MockHttpServletRequest("POST", uri); request.setServletPath(uri); return request; } private String serialize(XMLObject object) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } }
7,104
48.340278
119
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolverTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.saml2.core.LogoutRequest; import org.opensaml.saml.saml2.core.LogoutResponse; import org.opensaml.saml.saml2.core.StatusCode; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; /** * Tests for {@link OpenSamlLogoutResponseResolver} * * @author Josh Cummings */ public class OpenSamlLogoutResponseResolverTests { RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); OpenSamlLogoutResponseResolver logoutResponseResolver = new OpenSamlLogoutResponseResolver(null, this.relyingPartyRegistrationResolver); @Test public void resolveRedirectWhenAuthenticatedThenSuccess() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); MockHttpServletRequest request = new MockHttpServletRequest(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())); request.setParameter(Saml2ParameterNames.RELAY_STATE, "abcd"); Authentication authentication = authentication(registration); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutResponse saml2LogoutResponse = this.logoutResponseResolver.resolve(request, authentication); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIG_ALG)).isNotNull(); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIGNATURE)).isNotNull(); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.RELAY_STATE)).isSameAs("abcd"); Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); LogoutResponse logoutResponse = getLogoutResponse(saml2LogoutResponse.getSamlResponse(), binding); assertThat(logoutResponse.getStatus().getStatusCode().getValue()).isEqualTo(StatusCode.SUCCESS); } @Test public void resolvePostWhenAuthenticatedThenSuccess() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)).build(); MockHttpServletRequest request = new MockHttpServletRequest(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); request.setParameter(Saml2ParameterNames.SAML_REQUEST, Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())); request.setParameter(Saml2ParameterNames.RELAY_STATE, "abcd"); Authentication authentication = authentication(registration); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutResponse saml2LogoutResponse = this.logoutResponseResolver.resolve(request, authentication); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIG_ALG)).isNull(); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIGNATURE)).isNull(); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.RELAY_STATE)).isSameAs("abcd"); Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); LogoutResponse logoutResponse = getLogoutResponse(saml2LogoutResponse.getSamlResponse(), binding); assertThat(logoutResponse.getStatus().getStatusCode().getValue()).isEqualTo(StatusCode.SUCCESS); } // gh-10923 @Test public void resolvePostWithLineBreaksWhenAuthenticatedThenSuccess() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)).build(); MockHttpServletRequest request = new MockHttpServletRequest(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); String encoded = new StringBuffer( Saml2Utils.samlEncode(OpenSamlSigningUtils.serialize(logoutRequest).getBytes())).insert(10, "\r\n") .toString(); request.setParameter(Saml2ParameterNames.SAML_REQUEST, encoded); request.setParameter(Saml2ParameterNames.RELAY_STATE, "abcd"); Authentication authentication = authentication(registration); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); Saml2LogoutResponse saml2LogoutResponse = this.logoutResponseResolver.resolve(request, authentication); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIG_ALG)).isNull(); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.SIGNATURE)).isNull(); assertThat(saml2LogoutResponse.getParameter(Saml2ParameterNames.RELAY_STATE)).isSameAs("abcd"); Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleLogoutServiceBinding(); LogoutResponse logoutResponse = getLogoutResponse(saml2LogoutResponse.getSamlResponse(), binding); assertThat(logoutResponse.getStatus().getStatusCode().getValue()).isEqualTo(StatusCode.SUCCESS); } private Saml2Authentication authentication(RelyingPartyRegistration registration) { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", new HashMap<>()); principal.setRelyingPartyRegistrationId(registration.getRegistrationId()); return new Saml2Authentication(principal, "response", new ArrayList<>()); } private LogoutResponse getLogoutResponse(String saml2Response, Saml2MessageBinding binding) { if (binding == Saml2MessageBinding.REDIRECT) { saml2Response = Saml2Utils.samlInflate(Saml2Utils.samlDecode(saml2Response)); } else { saml2Response = new String(Saml2Utils.samlDecode(saml2Response), StandardCharsets.UTF_8); } try { Document document = XMLObjectProviderRegistrySupport.getParserPool() .parse(new ByteArrayInputStream(saml2Response.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutResponse) XMLObjectProviderRegistrySupport.getUnmarshallerFactory().getUnmarshaller(element) .unmarshall(element); } catch (Exception ex) { throw new Saml2Exception(ex); } } }
8,319
54.466667
114
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutRequestFilterTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockFilterChain; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.TestingAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.context.SecurityContextHolderStrategy; import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidator; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.authentication.logout.LogoutHandler; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; /** * Tests for {@link Saml2LogoutRequestFilter} */ public class Saml2LogoutRequestFilterTests { SecurityContextHolderStrategy securityContextHolderStrategy = mock(SecurityContextHolderStrategy.class); RelyingPartyRegistrationResolver relyingPartyRegistrationResolver = mock(RelyingPartyRegistrationResolver.class); Saml2LogoutRequestValidator logoutRequestValidator = mock(Saml2LogoutRequestValidator.class); LogoutHandler logoutHandler = mock(LogoutHandler.class); Saml2LogoutResponseResolver logoutResponseResolver = mock(Saml2LogoutResponseResolver.class); Saml2LogoutRequestFilter logoutRequestProcessingFilter = new Saml2LogoutRequestFilter( this.relyingPartyRegistrationResolver, this.logoutRequestValidator, this.logoutResponseResolver, this.logoutHandler); @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void doFilterWhenSamlRequestThenRedirects() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); MockHttpServletResponse response = new MockHttpServletResponse(); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); given(this.logoutRequestValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success()); Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration) .samlResponse("response").build(); given(this.logoutResponseResolver.resolve(any(), any())).willReturn(logoutResponse); this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verify(this.logoutRequestValidator).validate(any()); verify(this.logoutHandler).logout(any(), any(), any()); verify(this.logoutResponseResolver).resolve(any(), any()); String content = response.getHeader("Location"); assertThat(content).contains(Saml2ParameterNames.SAML_RESPONSE); assertThat(content) .startsWith(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()); } @Test public void doFilterWhenSamlRequestThenPosts() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)).build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); given(this.securityContextHolderStrategy.getContext()).willReturn(new SecurityContextImpl(authentication)); this.logoutRequestProcessingFilter.setSecurityContextHolderStrategy(this.securityContextHolderStrategy); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); MockHttpServletResponse response = new MockHttpServletResponse(); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); given(this.logoutRequestValidator.validate(any())).willReturn(Saml2LogoutValidatorResult.success()); Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration) .samlResponse("response").build(); given(this.logoutResponseResolver.resolve(any(), any())).willReturn(logoutResponse); this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verify(this.logoutRequestValidator).validate(any()); verify(this.logoutHandler).logout(any(), any(), any()); verify(this.logoutResponseResolver).resolve(any(), any()); String content = response.getContentAsString(); assertThat(content).contains(Saml2ParameterNames.SAML_RESPONSE); assertThat(content).contains(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()); assertThat(content).contains( "<meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">"); assertThat(content).contains("<script>window.onload = function() { document.forms[0].submit(); }</script>"); verify(this.securityContextHolderStrategy).getContext(); } @Test public void doFilterWhenRequestMismatchesThenNoLogout() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout"); request.setServletPath("/logout"); request.setParameter(Saml2ParameterNames.SAML_RESPONSE, "response"); MockHttpServletResponse response = new MockHttpServletResponse(); this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verifyNoInteractions(this.logoutRequestValidator, this.logoutHandler); } @Test public void doFilterWhenNoSamlRequestOrResponseThenNoLogout() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); MockHttpServletResponse response = new MockHttpServletResponse(); this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); verifyNoInteractions(this.logoutRequestValidator, this.logoutHandler); } @Test public void doFilterWhenValidationFailsThen401() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); MockHttpServletResponse response = new MockHttpServletResponse(); given(this.relyingPartyRegistrationResolver.resolve(request, null)).willReturn(registration); given(this.logoutRequestValidator.validate(any())) .willReturn(Saml2LogoutValidatorResult.withErrors(new Saml2Error("error", "description")).build()); this.logoutRequestProcessingFilter.doFilter(request, response, new MockFilterChain()); assertThat(response.getStatus()).isEqualTo(401); verifyNoInteractions(this.logoutHandler); } @Test public void doFilterWhenNoRelyingPartyLogoutThen401() throws Exception { Authentication authentication = new TestingAuthenticationToken("user", "password"); SecurityContextHolder.getContext().setAuthentication(authentication); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/logout/saml2/slo"); request.setServletPath("/logout/saml2/slo"); request.setParameter(Saml2ParameterNames.SAML_REQUEST, "request"); MockHttpServletResponse response = new MockHttpServletResponse(); RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().singleLogoutServiceLocation(null) .build(); given(this.relyingPartyRegistrationResolver.resolve(any(), any())).willReturn(registration); this.logoutRequestProcessingFilter.doFilterInternal(request, response, new MockFilterChain()); assertThat(response.getStatus()).isEqualTo(401); verifyNoInteractions(this.logoutHandler); } }
10,388
55.770492
130
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutSigningUtilsTests.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opensaml.saml.saml2.core.LogoutRequest; import org.opensaml.xmlsec.signature.Signature; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; /** * Test open SAML Logout signatures */ public class Saml2LogoutSigningUtilsTests { private RelyingPartyRegistration registration; @BeforeEach public void setup() { this.registration = RelyingPartyRegistration.withRegistrationId("saml-idp") .entityId("https://some.idp.example.com/entity-id").signingX509Credentials((c) -> { c.add(TestSaml2X509Credentials.relyingPartySigningCredential()); c.add(TestSaml2X509Credentials.assertingPartySigningCredential()); }).assertingPartyDetails((c) -> c.entityId("https://some.idp.example.com/entity-id") .singleSignOnServiceLocation("https://some.idp.example.com/service-location")) .build(); } @Test public void whenSigningLogoutRequestRPThenKeyInfoIsPartOfTheSignature() { LogoutRequest logoutRequest = TestOpenSamlObjects.relyingPartyLogoutRequest(this.registration); OpenSamlSigningUtils.sign(logoutRequest, this.registration); Signature signature = logoutRequest.getSignature(); assertThat(signature).isNotNull(); assertThat(signature.getKeyInfo()).isNotNull(); } }
2,277
38.275862
97
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2RelyingPartyInitiatedLogoutSuccessHandlerTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.util.ArrayList; import java.util.HashMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.mock; /** * Tests for {@link Saml2RelyingPartyInitiatedLogoutSuccessHandler} * * @author Josh Cummings */ public class Saml2RelyingPartyInitiatedLogoutSuccessHandlerTests { Saml2LogoutRequestResolver logoutRequestResolver = mock(Saml2LogoutRequestResolver.class); Saml2LogoutRequestRepository logoutRequestRepository = mock(Saml2LogoutRequestRepository.class); Saml2RelyingPartyInitiatedLogoutSuccessHandler logoutRequestSuccessHandler = new Saml2RelyingPartyInitiatedLogoutSuccessHandler( this.logoutRequestResolver); @BeforeEach public void setUp() { this.logoutRequestSuccessHandler.setLogoutRequestRepository(this.logoutRequestRepository); } @AfterEach public void tearDown() { SecurityContextHolder.clearContext(); } @Test public void onLogoutSuccessWhenRedirectThenRedirectsToAssertingParty() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full().build(); Authentication authentication = authentication(registration); SecurityContextHolder.getContext().setAuthentication(authentication); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest("request").build(); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/saml2/logout"); request.setServletPath("/saml2/logout"); MockHttpServletResponse response = new MockHttpServletResponse(); given(this.logoutRequestResolver.resolve(any(), any())).willReturn(logoutRequest); this.logoutRequestSuccessHandler.onLogoutSuccess(request, response, authentication); String content = response.getHeader("Location"); assertThat(content).contains(Saml2ParameterNames.SAML_REQUEST); assertThat(content).startsWith(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()); } @Test public void onLogoutSuccessWhenPostThenPostsToAssertingParty() throws Exception { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.full() .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)).build(); Authentication authentication = authentication(registration); SecurityContextHolder.getContext().setAuthentication(authentication); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest("request").build(); MockHttpServletRequest request = new MockHttpServletRequest("POST", "/saml2/logout"); request.setServletPath("/saml2/logout"); MockHttpServletResponse response = new MockHttpServletResponse(); given(this.logoutRequestResolver.resolve(any(), any())).willReturn(logoutRequest); this.logoutRequestSuccessHandler.onLogoutSuccess(request, response, authentication); String content = response.getContentAsString(); assertThat(content).contains(Saml2ParameterNames.SAML_REQUEST); assertThat(content).contains(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()); assertThat(content).contains( "<meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">"); assertThat(content).contains("<script>window.onload = function() { document.forms[0].submit(); }</script>"); } private Saml2Authentication authentication(RelyingPartyRegistration registration) { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", new HashMap<>()); principal.setRelyingPartyRegistrationId(registration.getRegistrationId()); return new Saml2Authentication(principal, "response", new ArrayList<>()); } }
5,573
48.767857
130
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/servlet/HttpSessionSaml2AuthenticationRequestRepositoryTests.java
/* * 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.servlet; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockHttpSession; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; import org.springframework.security.saml2.provider.service.web.HttpSessionSaml2AuthenticationRequestRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * @author Marcus Da Coregio */ public class HttpSessionSaml2AuthenticationRequestRepositoryTests { private static final String IDP_SSO_URL = "https://sso-url.example.com/IDP/SSO"; private MockHttpServletRequest request; private MockHttpServletResponse response; private HttpSessionSaml2AuthenticationRequestRepository authenticationRequestRepository; @BeforeEach public void setup() { this.request = new MockHttpServletRequest(); this.response = new MockHttpServletResponse(); this.authenticationRequestRepository = new HttpSessionSaml2AuthenticationRequestRepository(); } @Test public void loadAuthenticationRequestWhenInvalidSessionThenNull() { AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest).isNull(); } @Test public void loadAuthenticationRequestWhenNoAttributeInSessionThenNull() { this.request.getSession(); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest).isNull(); } @Test public void loadAuthenticationRequestWhenAttributeInSessionThenReturnsAuthenticationRequest() { AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class); given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(IDP_SSO_URL); this.request.getSession(); this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest.getAuthenticationRequestUri()).isEqualTo(IDP_SSO_URL); } @Test public void saveAuthenticationRequestWhenSessionDontExistsThenCreateAndSave() { AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class); this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest).isNotNull(); } @Test public void saveAuthenticationRequestWhenSessionExistsThenSave() { AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class); this.request.getSession(); this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest).isNotNull(); } @Test public void saveAuthenticationRequestWhenNullAuthenticationRequestThenDontSave() { this.request.getSession(); this.authenticationRequestRepository.saveAuthenticationRequest(null, this.request, this.response); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest).isNull(); } @Test public void removeAuthenticationRequestWhenInvalidSessionThenReturnNull() { AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .removeAuthenticationRequest(this.request, this.response); assertThat(authenticationRequest).isNull(); } @Test public void removeAuthenticationRequestWhenAttributeInSessionThenRemoveAuthenticationRequest() { AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class); given(mockAuthenticationRequest.getAuthenticationRequestUri()).willReturn(IDP_SSO_URL); this.request.getSession(); this.authenticationRequestRepository.saveAuthenticationRequest(mockAuthenticationRequest, this.request, this.response); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .removeAuthenticationRequest(this.request, this.response); AbstractSaml2AuthenticationRequest authenticationRequestAfterRemove = this.authenticationRequestRepository .loadAuthenticationRequest(this.request); assertThat(authenticationRequest.getAuthenticationRequestUri()).isEqualTo(IDP_SSO_URL); assertThat(authenticationRequestAfterRemove).isNull(); } @Test public void removeAuthenticationRequestWhenValidSessionNoAttributeThenReturnsNull() { MockHttpSession session = mock(MockHttpSession.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.setSession(session); AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository .removeAuthenticationRequest(request, this.response); verify(session).getAttribute(anyString()); assertThat(authenticationRequest).isNull(); } }
6,483
43.717241
112
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2PostAuthenticationRequestTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication; import org.junit.jupiter.api.Test; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.util.SerializationUtils; import static org.assertj.core.api.Assertions.assertThat; class Saml2PostAuthenticationRequestTests { private static final String IDP_SSO_URL = "https://sso-url.example.com/IDP/SSO"; @Test void serializeWhenDeserializeThenSameFields() { Saml2PostAuthenticationRequest authenticationRequest = getAuthenticationRequestBuilder().build(); byte[] bytes = SerializationUtils.serialize(authenticationRequest); Saml2PostAuthenticationRequest deserializedAuthenticationRequest = (Saml2PostAuthenticationRequest) SerializationUtils .deserialize(bytes); assertThat(deserializedAuthenticationRequest).usingRecursiveComparison().isEqualTo(authenticationRequest); } @Test void serializeWhenDeserializeAndCompareToOtherThenNotSame() { Saml2PostAuthenticationRequest authenticationRequest = getAuthenticationRequestBuilder().build(); Saml2PostAuthenticationRequest otherAuthenticationRequest = getAuthenticationRequestBuilder() .relayState("relay").build(); byte[] bytes = SerializationUtils.serialize(otherAuthenticationRequest); Saml2PostAuthenticationRequest deserializedAuthenticationRequest = (Saml2PostAuthenticationRequest) SerializationUtils .deserialize(bytes); assertThat(deserializedAuthenticationRequest).usingRecursiveComparison().isNotEqualTo(authenticationRequest); } private Saml2PostAuthenticationRequest.Builder getAuthenticationRequestBuilder() { return Saml2PostAuthenticationRequest .withRelyingPartyRegistration(TestRelyingPartyRegistrations.relyingPartyRegistration().build()) .samlRequest("request").authenticationRequestUri(IDP_SSO_URL); } }
2,498
42.842105
120
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSamlSigningUtilsTests.java
/* * 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 org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.opensaml.saml.saml2.core.Response; import org.opensaml.xmlsec.signature.Signature; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import static org.assertj.core.api.Assertions.assertThat; /** * Test open SAML signatures */ public class OpenSamlSigningUtilsTests { private RelyingPartyRegistration registration; @BeforeEach public void setup() { this.registration = RelyingPartyRegistration.withRegistrationId("saml-idp") .entityId("https://some.idp.example.com/entity-id").signingX509Credentials((c) -> { c.add(TestSaml2X509Credentials.relyingPartySigningCredential()); c.add(TestSaml2X509Credentials.assertingPartySigningCredential()); }).assertingPartyDetails((c) -> c.entityId("https://some.idp.example.com/entity-id") .singleSignOnServiceLocation("https://some.idp.example.com/service-location")) .build(); } @Test public void whenSigningAnObjectThenKeyInfoIsPartOfTheSignature() throws Exception { Response response = TestOpenSamlObjects.response(); OpenSamlSigningUtils.sign(response, this.registration); Signature signature = response.getSignature(); assertThat(signature).isNotNull(); assertThat(signature.getKeyInfo()).isNotNull(); } }
2,112
36.070175
97
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/OpenSaml4AuthenticationProviderTests.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.time.Duration; import java.time.Instant; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import javax.xml.namespace.QName; import com.fasterxml.jackson.databind.ObjectMapper; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.junit.jupiter.api.Test; 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.core.xml.schema.XSDateTime; import org.opensaml.core.xml.schema.impl.XSDateTimeBuilder; import org.opensaml.saml.common.SignableSAMLObject; import org.opensaml.saml.common.assertion.ValidationContext; import org.opensaml.saml.saml2.assertion.SAML2AssertionValidationParameters; 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.AttributeValue; import org.opensaml.saml.saml2.core.Conditions; import org.opensaml.saml.saml2.core.EncryptedAssertion; import org.opensaml.saml.saml2.core.EncryptedAttribute; import org.opensaml.saml.saml2.core.EncryptedID; import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.OneTimeUse; import org.opensaml.saml.saml2.core.Response; import org.opensaml.saml.saml2.core.StatusCode; import org.opensaml.saml.saml2.core.SubjectConfirmation; import org.opensaml.saml.saml2.core.SubjectConfirmationData; import org.opensaml.saml.saml2.core.impl.AttributeBuilder; import org.opensaml.saml.saml2.core.impl.EncryptedAssertionBuilder; import org.opensaml.saml.saml2.core.impl.EncryptedIDBuilder; import org.opensaml.saml.saml2.core.impl.NameIDBuilder; import org.opensaml.xmlsec.encryption.impl.EncryptedDataBuilder; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.w3c.dom.Element; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.Authentication; import org.springframework.security.jackson2.SecurityJackson2Modules; 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.Saml2ResponseValidatorResult; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.OpenSaml4AuthenticationProvider.ResponseToken; import org.springframework.security.saml2.provider.service.authentication.TestCustomOpenSamlObjects.CustomOpenSamlObject; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.util.StringUtils; 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.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; /** * Tests for {@link OpenSaml4AuthenticationProvider} * * @author Filip Hanik * @author Josh Cummings */ public class OpenSaml4AuthenticationProviderTests { private static String DESTINATION = "https://localhost/login/saml2/sso/idp-alias"; private static String RELYING_PARTY_ENTITY_ID = "https://localhost/saml2/service-provider-metadata/idp-alias"; private static String ASSERTING_PARTY_ENTITY_ID = "https://some.idp.test/saml2/idp"; private OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); private Saml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("name", Collections.emptyMap()); private Saml2Authentication authentication = new Saml2Authentication(this.principal, "response", Collections.emptyList()); @Test public void supportsWhenSaml2AuthenticationTokenThenReturnTrue() { assertThat(this.provider.supports(Saml2AuthenticationToken.class)) .withFailMessage( OpenSaml4AuthenticationProvider.class + "should support " + Saml2AuthenticationToken.class) .isTrue(); } @Test public void supportsWhenNotSaml2AuthenticationTokenThenReturnFalse() { assertThat(!this.provider.supports(Authentication.class)) .withFailMessage(OpenSaml4AuthenticationProvider.class + "should not support " + Authentication.class) .isTrue(); } @Test public void authenticateWhenUnknownDataClassThenThrowAuthenticationException() { Assertion assertion = (Assertion) XMLObjectProviderRegistrySupport.getBuilderFactory() .getBuilder(Assertion.DEFAULT_ELEMENT_NAME).buildObject(Assertion.DEFAULT_ELEMENT_NAME); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate( new Saml2AuthenticationToken(verifying(registration()).build(), serialize(assertion)))) .satisfies(errorOf(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA)); } @Test public void authenticateWhenXmlErrorThenThrowAuthenticationException() { Saml2AuthenticationToken token = new Saml2AuthenticationToken(verifying(registration()).build(), "invalid xml"); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA)); } @Test public void authenticateWhenInvalidDestinationThenThrowAuthenticationException() { Response response = response(DESTINATION + "invalid", ASSERTING_PARTY_ENTITY_ID); response.getAssertions().add(assertion()); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.INVALID_DESTINATION)); } @Test public void authenticateWhenNoAssertionsPresentThenThrowAuthenticationException() { Saml2AuthenticationToken token = token(); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, "No assertions found in response.")); } @Test public void authenticateWhenInvalidSignatureOnAssertionThenThrowAuthenticationException() { Response response = response(); response.getAssertions().add(assertion()); Saml2AuthenticationToken token = token(response, verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.INVALID_SIGNATURE)); } @Test public void authenticateWhenOpenSAMLValidationErrorThenThrowAuthenticationException() { Response response = response(); Assertion assertion = assertion(); assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData() .setNotOnOrAfter(Instant.now().minus(Duration.ofDays(3))); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.INVALID_ASSERTION)); } @Test public void authenticateWhenMissingSubjectThenThrowAuthenticationException() { Response response = response(); Assertion assertion = assertion(); assertion.setSubject(null); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.SUBJECT_NOT_FOUND)); } @Test public void authenticateWhenUsernameMissingThenThrowAuthenticationException() { Response response = response(); Assertion assertion = assertion(); assertion.getSubject().getNameID().setValue(null); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.SUBJECT_NOT_FOUND)); } @Test public void authenticateWhenAssertionContainsValidationAddressThenItSucceeds() { Response response = response(); Assertion assertion = assertion(); assertion.getSubject().getSubjectConfirmations() .forEach((sc) -> sc.getSubjectConfirmationData().setAddress("10.10.10.10")); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); this.provider.authenticate(token); } @Test public void evaluateInResponseToSucceedsWhenInResponseToInResponseAndAssertionsMatchRequestID() { Response response = response(); response.setInResponseTo("SAML2"); response.getAssertions().add(signed(assertion("SAML2"))); response.getAssertions().add(signed(assertion("SAML2"))); AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mockedStoredAuthenticationRequest("SAML2"); Saml2AuthenticationToken token = token(response, verifying(registration()), mockAuthenticationRequest); this.provider.authenticate(token); } @Test public void evaluateInResponseToSucceedsWhenInResponseToInAssertionOnlyMatchRequestID() { Response response = response(); response.getAssertions().add(signed(assertion())); response.getAssertions().add(signed(assertion("SAML2"))); AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mockedStoredAuthenticationRequest("SAML2"); Saml2AuthenticationToken token = token(response, verifying(registration()), mockAuthenticationRequest); this.provider.authenticate(token); } @Test public void evaluateInResponseToFailsWhenInResponseToInAssertionMismatchWithRequestID() { Response response = response(); response.setInResponseTo("SAML2"); response.getAssertions().add(signed(assertion("SAML2"))); response.getAssertions().add(signed(assertion("BAD"))); AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mockedStoredAuthenticationRequest("SAML2"); Saml2AuthenticationToken token = token(response, verifying(registration()), mockAuthenticationRequest); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)).withStackTraceContaining("invalid_assertion"); } @Test public void evaluateInResponseToFailsWhenInResponseToInAssertionOnlyAndMismatchWithRequestID() { Response response = response(); response.getAssertions().add(signed(assertion())); response.getAssertions().add(signed(assertion("BAD"))); AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mockedStoredAuthenticationRequest("SAML2"); Saml2AuthenticationToken token = token(response, verifying(registration()), mockAuthenticationRequest); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)).withStackTraceContaining("invalid_assertion"); } @Test public void evaluateInResponseToFailsWhenInResponseInToResponseMismatchWithRequestID() { Response response = response(); response.setInResponseTo("BAD"); response.getAssertions().add(signed(assertion("SAML2"))); response.getAssertions().add(signed(assertion("SAML2"))); AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mockedStoredAuthenticationRequest("SAML2"); Saml2AuthenticationToken token = token(response, verifying(registration()), mockAuthenticationRequest); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)).withStackTraceContaining("invalid_in_response_to"); } @Test public void evaluateInResponseToFailsWhenInResponseToInResponseButNoSavedRequest() { Response response = response(); response.setInResponseTo("BAD"); Saml2AuthenticationToken token = token(response, verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)).withStackTraceContaining("invalid_in_response_to"); } @Test public void evaluateInResponseToSucceedsWhenNoInResponseToInResponseOrAssertions() { Response response = response(); response.getAssertions().add(signed(assertion())); AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mockedStoredAuthenticationRequest("SAML2"); Saml2AuthenticationToken token = token(response, verifying(registration()), mockAuthenticationRequest); this.provider.authenticate(token); } @Test public void authenticateWhenAssertionContainsAttributesThenItSucceeds() { Response response = response(); Assertion assertion = assertion(); List<AttributeStatement> attributes = attributeStatements(); assertion.getAttributeStatements().addAll(attributes); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); Authentication authentication = this.provider.authenticate(token); Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) authentication.getPrincipal(); Map<String, Object> expected = new LinkedHashMap<>(); expected.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); expected.put("name", Collections.singletonList("John Doe")); expected.put("age", Collections.singletonList(21)); expected.put("website", Collections.singletonList("https://johndoe.com/")); expected.put("registered", Collections.singletonList(true)); Instant registeredDate = Instant.parse("1970-01-01T00:00:00Z"); expected.put("registeredDate", Collections.singletonList(registeredDate)); expected.put("role", Arrays.asList("RoleOne", "RoleTwo")); // gh-11042 assertThat((String) principal.getFirstAttribute("name")).isEqualTo("John Doe"); assertThat(principal.getAttributes()).isEqualTo(expected); assertThat(principal.getSessionIndexes()).contains("session-index"); } // gh-11785 @Test public void deserializeWhenAssertionContainsAttributesThenWorks() throws Exception { ObjectMapper mapper = new ObjectMapper(); ClassLoader loader = getClass().getClassLoader(); mapper.registerModules(SecurityJackson2Modules.getModules(loader)); Response response = response(); Assertion assertion = assertion(); List<AttributeStatement> attributes = TestOpenSamlObjects.attributeStatements(); assertion.getAttributeStatements().addAll(attributes); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); Authentication authentication = this.provider.authenticate(token); String result = mapper.writeValueAsString(authentication); mapper.readValue(result, Authentication.class); } @Test public void authenticateWhenAssertionContainsCustomAttributesThenItSucceeds() { Response response = response(); Assertion assertion = assertion(); AttributeStatement attribute = TestOpenSamlObjects.customAttributeStatement("Address", TestCustomOpenSamlObjects.instance()); assertion.getAttributeStatements().add(attribute); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); Authentication authentication = this.provider.authenticate(token); Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) authentication.getPrincipal(); CustomOpenSamlObject address = (CustomOpenSamlObject) principal.getAttribute("Address").get(0); assertThat(address.getStreet()).isEqualTo("Test Street"); assertThat(address.getStreetNumber()).isEqualTo("1"); assertThat(address.getZIP()).isEqualTo("11111"); assertThat(address.getCity()).isEqualTo("Test City"); } @Test public void authenticateWhenEncryptedAssertionWithoutSignatureThenItFails() { Response response = response(); EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion(), TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); Saml2AuthenticationToken token = token(response, decrypting(verifying(registration()))); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.INVALID_SIGNATURE, "Did not decrypt response")); } @Test public void authenticateWhenEncryptedAssertionWithSignatureThenItSucceeds() { Response response = response(); Assertion assertion = TestOpenSamlObjects.signed(assertion(), TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion, TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); Saml2AuthenticationToken token = token(signed(response), decrypting(verifying(registration()))); this.provider.authenticate(token); } @Test public void authenticateWhenEncryptedAssertionWithResponseSignatureThenItSucceeds() { Response response = response(); EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion(), TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); Saml2AuthenticationToken token = token(signed(response), decrypting(verifying(registration()))); this.provider.authenticate(token); } @Test public void authenticateWhenEncryptedNameIdWithSignatureThenItSucceeds() { Response response = response(); Assertion assertion = assertion(); NameID nameId = assertion.getSubject().getNameID(); EncryptedID encryptedID = TestOpenSamlObjects.encrypted(nameId, TestSaml2X509Credentials.assertingPartyEncryptingCredential()); assertion.getSubject().setNameID(null); assertion.getSubject().setEncryptedID(encryptedID); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, decrypting(verifying(registration()))); this.provider.authenticate(token); } @Test public void authenticateWhenEncryptedAttributeThenDecrypts() { Response response = response(); Assertion assertion = assertion(); EncryptedAttribute attribute = TestOpenSamlObjects.encrypted("name", "value", TestSaml2X509Credentials.assertingPartyEncryptingCredential()); AttributeStatement statement = build(AttributeStatement.DEFAULT_ELEMENT_NAME); statement.getEncryptedAttributes().add(attribute); assertion.getAttributeStatements().add(statement); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), decrypting(verifying(registration()))); Saml2Authentication authentication = (Saml2Authentication) this.provider.authenticate(token); Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) authentication.getPrincipal(); assertThat(principal.getAttribute("name")).containsExactly("value"); } @Test public void authenticateWhenDecryptionKeysAreMissingThenThrowAuthenticationException() { Response response = response(); EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion(), TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.DECRYPTION_ERROR, "Failed to decrypt EncryptedData")); } @Test public void authenticateWhenDecryptionKeysAreWrongThenThrowAuthenticationException() { Response response = response(); EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion(), TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); Saml2AuthenticationToken token = token(signed(response), registration() .decryptionX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartyPrivateCredential()))); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.DECRYPTION_ERROR, "Failed to decrypt EncryptedData")); } @Test public void authenticateWhenAuthenticationHasDetailsThenSucceeds() { Response response = response(); Assertion assertion = assertion(); assertion.getSubject().getSubjectConfirmations() .forEach((sc) -> sc.getSubjectConfirmationData().setAddress("10.10.10.10")); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); token.setDetails("some-details"); Authentication authentication = this.provider.authenticate(token); assertThat(authentication.getDetails()).isEqualTo("some-details"); } @Test public void writeObjectWhenTypeIsSaml2AuthenticationThenNoException() throws IOException { Response response = response(); Assertion assertion = TestOpenSamlObjects.signed(assertion(), TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); EncryptedAssertion encryptedAssertion = TestOpenSamlObjects.encrypted(assertion, TestSaml2X509Credentials.assertingPartyEncryptingCredential()); response.getEncryptedAssertions().add(encryptedAssertion); Saml2AuthenticationToken token = token(signed(response), decrypting(verifying(registration()))); Saml2Authentication authentication = (Saml2Authentication) this.provider.authenticate(token); // the following code will throw an exception if authentication isn't serializable ByteArrayOutputStream byteStream = new ByteArrayOutputStream(1024); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream); objectOutputStream.writeObject(authentication); objectOutputStream.flush(); } @Test public void createDefaultAssertionValidatorWhenAssertionThenValidates() { Response response = TestOpenSamlObjects.signedResponseWithOneAssertion(); Assertion assertion = response.getAssertions().get(0); OpenSaml4AuthenticationProvider.AssertionToken assertionToken = new OpenSaml4AuthenticationProvider.AssertionToken( assertion, token()); assertThat( OpenSaml4AuthenticationProvider.createDefaultAssertionValidator().convert(assertionToken).hasErrors()) .isFalse(); } @Test public void authenticateWhenDelegatingToDefaultAssertionValidatorThenUses() { OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); // @formatter:off provider.setAssertionValidator((assertionToken) -> OpenSaml4AuthenticationProvider .createDefaultAssertionValidator((token) -> new ValidationContext()) .convert(assertionToken) .concat(new Saml2Error("wrong error", "wrong error")) ); // @formatter:on Response response = response(); Assertion assertion = assertion(); OneTimeUse oneTimeUse = build(OneTimeUse.DEFAULT_ELEMENT_NAME); assertion.getConditions().getConditions().add(oneTimeUse); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); // @formatter:off assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> provider.authenticate(token)).isInstanceOf(Saml2AuthenticationException.class) .satisfies((error) -> assertThat(error.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_ASSERTION)); // @formatter:on } // gh-11675 @Test public void authenticateWhenUsingCustomAssertionValidatorThenUses() { OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); Consumer<Map<String, Object>> validationParameters = mock(Consumer.class); // @formatter:off provider.setAssertionValidator(OpenSaml4AuthenticationProvider .createDefaultAssertionValidatorWithParameters(validationParameters)); // @formatter:on Response response = response(); Assertion assertion = assertion(); OneTimeUse oneTimeUse = build(OneTimeUse.DEFAULT_ELEMENT_NAME); assertion.getConditions().getConditions().add(oneTimeUse); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); provider.authenticate(token); verify(validationParameters).accept(any()); } @Test public void authenticateWhenCustomAssertionValidatorThenUses() { Converter<OpenSaml4AuthenticationProvider.AssertionToken, Saml2ResponseValidatorResult> validator = mock( Converter.class); OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); // @formatter:off provider.setAssertionValidator((assertionToken) -> OpenSaml4AuthenticationProvider.createDefaultAssertionValidator() .convert(assertionToken) .concat(validator.convert(assertionToken)) ); // @formatter:on Response response = response(); Assertion assertion = assertion(); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); given(validator.convert(any(OpenSaml4AuthenticationProvider.AssertionToken.class))) .willReturn(Saml2ResponseValidatorResult.success()); provider.authenticate(token); verify(validator).convert(any(OpenSaml4AuthenticationProvider.AssertionToken.class)); } @Test public void authenticateWhenDefaultConditionValidatorNotUsedThenSignatureStillChecked() { OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); provider.setAssertionValidator((assertionToken) -> Saml2ResponseValidatorResult.success()); Response response = response(); Assertion assertion = assertion(); TestOpenSamlObjects.signed(assertion, TestSaml2X509Credentials.relyingPartyDecryptingCredential(), RELYING_PARTY_ENTITY_ID); // broken // signature response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); // @formatter:off assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> provider.authenticate(token)) .satisfies((error) -> assertThat(error.getSaml2Error().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_SIGNATURE)); // @formatter:on } @Test public void authenticateWhenValidationContextCustomizedThenUsers() { Map<String, Object> parameters = new HashMap<>(); parameters.put(SAML2AssertionValidationParameters.SC_VALID_RECIPIENTS, Collections.singleton("blah")); ValidationContext context = mock(ValidationContext.class); given(context.getStaticParameters()).willReturn(parameters); OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); provider.setAssertionValidator( OpenSaml4AuthenticationProvider.createDefaultAssertionValidator((assertionToken) -> context)); Response response = response(); Assertion assertion = assertion(); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); // @formatter:off assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> provider.authenticate(token)).isInstanceOf(Saml2AuthenticationException.class) .satisfies((error) -> assertThat(error).hasMessageContaining("Invalid assertion")); // @formatter:on verify(context, atLeastOnce()).getStaticParameters(); } @Test public void authenticateWithSHA1SignatureThenItSucceeds() throws Exception { Response response = response(); Assertion assertion = TestOpenSamlObjects.signed(assertion(), TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID, SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(response, verifying(registration())); this.provider.authenticate(token); } @Test public void setAssertionValidatorWhenNullThenIllegalArgument() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.provider.setAssertionValidator(null)); // @formatter:on } @Test public void createDefaultResponseAuthenticationConverterWhenResponseThenConverts() { Response response = TestOpenSamlObjects.signedResponseWithOneAssertion(); Saml2AuthenticationToken token = token(response, verifying(registration())); ResponseToken responseToken = new ResponseToken(response, token); Saml2Authentication authentication = OpenSaml4AuthenticationProvider .createDefaultResponseAuthenticationConverter().convert(responseToken); assertThat(authentication.getName()).isEqualTo("test@saml.user"); } @Test public void authenticateWhenResponseAuthenticationConverterConfiguredThenUses() { Converter<ResponseToken, Saml2Authentication> authenticationConverter = mock(Converter.class); OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); provider.setResponseAuthenticationConverter(authenticationConverter); Response response = TestOpenSamlObjects.signedResponseWithOneAssertion(); Saml2AuthenticationToken token = token(response, verifying(registration())); provider.authenticate(token); verify(authenticationConverter).convert(any()); } @Test public void setResponseAuthenticationConverterWhenNullThenIllegalArgument() { // @formatter:off assertThatIllegalArgumentException() .isThrownBy(() -> this.provider.setResponseAuthenticationConverter(null)); // @formatter:on } @Test public void setResponseElementsDecrypterWhenNullThenIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setResponseElementsDecrypter(null)); } @Test public void setAssertionElementsDecrypterWhenNullThenIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setAssertionElementsDecrypter(null)); } @Test public void authenticateWhenCustomResponseElementsDecrypterThenDecryptsResponse() { Response response = response(); Assertion assertion = assertion(); response.getEncryptedAssertions().add(new EncryptedAssertionBuilder().buildObject()); TestOpenSamlObjects.signed(response, TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); Saml2AuthenticationToken token = token(response, verifying(registration())); this.provider .setResponseElementsDecrypter((tuple) -> tuple.getResponse().getAssertions().add(signed(assertion))); Authentication authentication = this.provider.authenticate(token); assertThat(authentication.getName()).isEqualTo("test@saml.user"); } @Test public void authenticateWhenCustomAssertionElementsDecrypterThenDecryptsAssertion() { Response response = response(); Assertion assertion = assertion(); EncryptedID id = new EncryptedIDBuilder().buildObject(); id.setEncryptedData(new EncryptedDataBuilder().buildObject()); assertion.getSubject().setEncryptedID(id); response.getAssertions().add(signed(assertion)); Saml2AuthenticationToken token = token(response, verifying(registration())); this.provider.setAssertionElementsDecrypter((tuple) -> { NameID name = new NameIDBuilder().buildObject(); name.setValue("decrypted name"); tuple.getAssertion().getSubject().setNameID(name); }); Authentication authentication = this.provider.authenticate(token); assertThat(authentication.getName()).isEqualTo("decrypted name"); } @Test public void authenticateWhenResponseStatusIsNotSuccessThenFails() { Response response = TestOpenSamlObjects.signedResponseWithOneAssertion( (r) -> r.setStatus(TestOpenSamlObjects.status(StatusCode.AUTHN_FAILED))); Saml2AuthenticationToken token = token(response, verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class) .isThrownBy(() -> this.provider.authenticate(token)) .satisfies(errorOf(Saml2ErrorCodes.INVALID_RESPONSE, "Invalid status")); } @Test public void authenticateWhenResponseStatusIsSuccessThenSucceeds() { Response response = TestOpenSamlObjects .signedResponseWithOneAssertion((r) -> r.setStatus(TestOpenSamlObjects.successStatus())); Saml2AuthenticationToken token = token(response, verifying(registration())); Authentication authentication = this.provider.authenticate(token); assertThat(authentication.getName()).isEqualTo("test@saml.user"); } @Test public void setResponseValidatorWhenNullThenIllegalArgument() { assertThatIllegalArgumentException().isThrownBy(() -> this.provider.setResponseValidator(null)); } @Test public void authenticateWhenCustomResponseValidatorThenUses() { Converter<OpenSaml4AuthenticationProvider.ResponseToken, Saml2ResponseValidatorResult> validator = mock( Converter.class); OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); // @formatter:off provider.setResponseValidator((responseToken) -> OpenSaml4AuthenticationProvider.createDefaultResponseValidator() .convert(responseToken) .concat(validator.convert(responseToken)) ); // @formatter:on Response response = response(); Assertion assertion = assertion(); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); given(validator.convert(any(OpenSaml4AuthenticationProvider.ResponseToken.class))) .willReturn(Saml2ResponseValidatorResult.success()); provider.authenticate(token); verify(validator).convert(any(OpenSaml4AuthenticationProvider.ResponseToken.class)); } @Test public void authenticateWhenAssertionIssuerNotValidThenFailsWithInvalidIssuer() { OpenSaml4AuthenticationProvider provider = new OpenSaml4AuthenticationProvider(); Response response = response(); Assertion assertion = assertion(); assertion.setIssuer(TestOpenSamlObjects.issuer("https://invalid.idp.test/saml2/idp")); response.getAssertions().add(assertion); Saml2AuthenticationToken token = token(signed(response), verifying(registration())); assertThatExceptionOfType(Saml2AuthenticationException.class).isThrownBy(() -> provider.authenticate(token)) .withMessageContaining("did not match any valid issuers"); } private <T extends XMLObject> T build(QName qName) { return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); } 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); } } private Consumer<Saml2AuthenticationException> errorOf(String errorCode) { return errorOf(errorCode, null); } private Consumer<Saml2AuthenticationException> errorOf(String errorCode, String description) { return (ex) -> { assertThat(ex.getSaml2Error().getErrorCode()).isEqualTo(errorCode); if (StringUtils.hasText(description)) { assertThat(ex.getSaml2Error().getDescription()).contains(description); } }; } private Response response() { Response response = TestOpenSamlObjects.response(); response.setIssueInstant(Instant.now()); return response; } private Response response(String destination, String issuerEntityId) { Response response = TestOpenSamlObjects.response(destination, issuerEntityId); response.setIssueInstant(Instant.now()); return response; } private Assertion assertion(String inResponseTo) { Assertion assertion = TestOpenSamlObjects.assertion(); assertion.setIssueInstant(Instant.now()); for (SubjectConfirmation confirmation : assertion.getSubject().getSubjectConfirmations()) { SubjectConfirmationData data = confirmation.getSubjectConfirmationData(); data.setNotBefore(Instant.now().minus(Duration.ofMillis(5 * 60 * 1000))); data.setNotOnOrAfter(Instant.now().plus(Duration.ofMillis(5 * 60 * 1000))); if (StringUtils.hasText(inResponseTo)) { data.setInResponseTo(inResponseTo); } } Conditions conditions = assertion.getConditions(); conditions.setNotBefore(Instant.now().minus(Duration.ofMillis(5 * 60 * 1000))); conditions.setNotOnOrAfter(Instant.now().plus(Duration.ofMillis(5 * 60 * 1000))); return assertion; } private Assertion assertion() { return assertion(null); } private <T extends SignableSAMLObject> T signed(T toSign) { TestOpenSamlObjects.signed(toSign, TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); return toSign; } private List<AttributeStatement> attributeStatements() { List<AttributeStatement> attributeStatements = TestOpenSamlObjects.attributeStatements(); AttributeBuilder attributeBuilder = new AttributeBuilder(); Attribute registeredDateAttr = attributeBuilder.buildObject(); registeredDateAttr.setName("registeredDate"); XSDateTime registeredDate = new XSDateTimeBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSDateTime.TYPE_NAME); registeredDate.setValue(Instant.parse("1970-01-01T00:00:00Z")); registeredDateAttr.getAttributeValues().add(registeredDate); attributeStatements.iterator().next().getAttributes().add(registeredDateAttr); return attributeStatements; } private Saml2AuthenticationToken token() { Response response = response(); RelyingPartyRegistration registration = verifying(registration()).build(); return new Saml2AuthenticationToken(registration, serialize(response)); } private Saml2AuthenticationToken token(Response response, RelyingPartyRegistration.Builder registration) { return new Saml2AuthenticationToken(registration.build(), serialize(response)); } private Saml2AuthenticationToken token(Response response, RelyingPartyRegistration.Builder registration, AbstractSaml2AuthenticationRequest authenticationRequest) { return new Saml2AuthenticationToken(registration.build(), serialize(response), authenticationRequest); } private AbstractSaml2AuthenticationRequest mockedStoredAuthenticationRequest(String requestId) { AbstractSaml2AuthenticationRequest mockAuthenticationRequest = mock(AbstractSaml2AuthenticationRequest.class); given(mockAuthenticationRequest.getId()).willReturn(requestId); return mockAuthenticationRequest; } private RelyingPartyRegistration.Builder registration() { return TestRelyingPartyRegistrations.noCredentials().entityId(RELYING_PARTY_ENTITY_ID) .assertionConsumerServiceLocation(DESTINATION) .assertingPartyDetails((party) -> party.entityId(ASSERTING_PARTY_ENTITY_ID)); } private RelyingPartyRegistration.Builder verifying(RelyingPartyRegistration.Builder builder) { return builder.assertingPartyDetails((party) -> party .verificationX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))); } private RelyingPartyRegistration.Builder decrypting(RelyingPartyRegistration.Builder builder) { return builder .decryptionX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyDecryptingCredential())); } }
40,461
46.49061
121
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2Authentications.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication; import java.util.Collections; import org.springframework.security.core.authority.AuthorityUtils; /** * Tests instances for {@link Saml2Authentication} * * @author Josh Cummings */ public final class TestSaml2Authentications { private TestSaml2Authentications() { } public static Saml2Authentication authentication() { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", Collections.emptyMap()); principal.setRelyingPartyRegistrationId("simplesamlphp"); return new Saml2Authentication(principal, "response", AuthorityUtils.createAuthorityList("ROLE_USER")); } }
1,326
31.365854
105
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestCustomOpenSamlObjects.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication; import java.util.Collections; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.xml.namespace.QName; import net.shibboleth.utilities.java.support.xml.ElementSupport; import org.opensaml.core.xml.AbstractXMLObject; import org.opensaml.core.xml.AbstractXMLObjectBuilder; import org.opensaml.core.xml.ElementExtensibleXMLObject; import org.opensaml.core.xml.Namespace; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.AbstractXMLObjectMarshaller; import org.opensaml.core.xml.io.AbstractXMLObjectUnmarshaller; import org.opensaml.core.xml.io.UnmarshallingException; import org.opensaml.core.xml.schema.XSAny; import org.opensaml.core.xml.schema.impl.XSAnyBuilder; import org.opensaml.core.xml.util.IndexedXMLObjectChildrenList; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.saml2.core.AttributeValue; import org.w3c.dom.Element; import org.springframework.security.saml2.core.OpenSamlInitializationService; public final class TestCustomOpenSamlObjects { static { OpenSamlInitializationService.initialize(); XMLObjectProviderRegistrySupport.getMarshallerFactory().registerMarshaller(CustomOpenSamlObject.TYPE_NAME, new TestCustomOpenSamlObjects.CustomSamlObjectMarshaller()); XMLObjectProviderRegistrySupport.getUnmarshallerFactory().registerUnmarshaller(CustomOpenSamlObject.TYPE_NAME, new TestCustomOpenSamlObjects.CustomSamlObjectUnmarshaller()); } public static CustomOpenSamlObject instance() { CustomOpenSamlObject samlObject = new TestCustomOpenSamlObjects.CustomSamlObjectBuilder() .buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, CustomOpenSamlObject.TYPE_NAME); XSAny street = new XSAnyBuilder().buildObject(CustomOpenSamlObject.CUSTOM_NS, "Street", CustomOpenSamlObject.TYPE_CUSTOM_PREFIX); street.setTextContent("Test Street"); samlObject.getUnknownXMLObjects().add(street); XSAny streetNumber = new XSAnyBuilder().buildObject(CustomOpenSamlObject.CUSTOM_NS, "Number", CustomOpenSamlObject.TYPE_CUSTOM_PREFIX); streetNumber.setTextContent("1"); samlObject.getUnknownXMLObjects().add(streetNumber); XSAny zip = new XSAnyBuilder().buildObject(CustomOpenSamlObject.CUSTOM_NS, "ZIP", CustomOpenSamlObject.TYPE_CUSTOM_PREFIX); zip.setTextContent("11111"); samlObject.getUnknownXMLObjects().add(zip); XSAny city = new XSAnyBuilder().buildObject(CustomOpenSamlObject.CUSTOM_NS, "City", CustomOpenSamlObject.TYPE_CUSTOM_PREFIX); city.setTextContent("Test City"); samlObject.getUnknownXMLObjects().add(city); return samlObject; } private TestCustomOpenSamlObjects() { } public interface CustomOpenSamlObject extends ElementExtensibleXMLObject { String TYPE_LOCAL_NAME = "CustomType"; String TYPE_CUSTOM_PREFIX = "custom"; String CUSTOM_NS = "https://custom.com/schema/custom"; /** QName of the CustomType type. */ QName TYPE_NAME = new QName(CUSTOM_NS, TYPE_LOCAL_NAME, TYPE_CUSTOM_PREFIX); String getStreet(); String getStreetNumber(); String getZIP(); String getCity(); } public static class CustomOpenSamlObjectImpl extends AbstractXMLObject implements CustomOpenSamlObject { @Nonnull private IndexedXMLObjectChildrenList<XMLObject> unknownXMLObjects; /** * Constructor. * @param namespaceURI the namespace the element is in * @param elementLocalName the local name of the XML element this Object * represents * @param namespacePrefix the prefix for the given namespace */ protected CustomOpenSamlObjectImpl(@Nullable String namespaceURI, @Nonnull String elementLocalName, @Nullable String namespacePrefix) { super(namespaceURI, elementLocalName, namespacePrefix); super.getNamespaceManager().registerNamespaceDeclaration(new Namespace(CUSTOM_NS, TYPE_CUSTOM_PREFIX)); this.unknownXMLObjects = new IndexedXMLObjectChildrenList<>(this); } @Nonnull @Override public List<XMLObject> getUnknownXMLObjects() { return this.unknownXMLObjects; } @Nonnull @Override public List<XMLObject> getUnknownXMLObjects(@Nonnull QName typeOrName) { return (List<XMLObject>) this.unknownXMLObjects.subList(typeOrName); } @Nullable @Override public List<XMLObject> getOrderedChildren() { return Collections.unmodifiableList(this.unknownXMLObjects); } @Override public String getStreet() { return ((XSAny) getOrderedChildren().get(0)).getTextContent(); } @Override public String getStreetNumber() { return ((XSAny) getOrderedChildren().get(1)).getTextContent(); } @Override public String getZIP() { return ((XSAny) getOrderedChildren().get(2)).getTextContent(); } @Override public String getCity() { return ((XSAny) getOrderedChildren().get(3)).getTextContent(); } } public static class CustomSamlObjectBuilder extends AbstractXMLObjectBuilder<CustomOpenSamlObject> { @Nonnull @Override public CustomOpenSamlObject buildObject(@Nullable String namespaceURI, @Nonnull String localName, @Nullable String namespacePrefix) { return new CustomOpenSamlObjectImpl(namespaceURI, localName, namespacePrefix); } } public static class CustomSamlObjectMarshaller extends AbstractXMLObjectMarshaller { public CustomSamlObjectMarshaller() { super(); } @Override protected void marshallElementContent(@Nonnull XMLObject xmlObject, @Nonnull Element domElement) { final CustomOpenSamlObject customSamlObject = (CustomOpenSamlObject) xmlObject; for (XMLObject object : customSamlObject.getOrderedChildren()) { ElementSupport.appendChildElement(domElement, object.getDOM()); } } } public static class CustomSamlObjectUnmarshaller extends AbstractXMLObjectUnmarshaller { public CustomSamlObjectUnmarshaller() { super(); } @Override protected void processChildElement(@Nonnull XMLObject parentXMLObject, @Nonnull XMLObject childXMLObject) throws UnmarshallingException { final CustomOpenSamlObject customSamlObject = (CustomOpenSamlObject) parentXMLObject; super.processChildElement(customSamlObject, childXMLObject); customSamlObject.getUnknownXMLObjects().add(childXMLObject); } @Nonnull @Override protected XMLObject buildXMLObject(@Nonnull Element domElement) { return new CustomOpenSamlObjectImpl(SAMLConstants.SAML20_NS, AttributeValue.DEFAULT_ELEMENT_LOCAL_NAME, CustomOpenSamlObject.TYPE_CUSTOM_PREFIX); } } }
7,186
32.741784
112
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestSaml2AuthenticationTokens.java
/* * 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 org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; /** * Tests instances for {@link Saml2AuthenticationToken} * * @author Marcus Da Coregio */ public final class TestSaml2AuthenticationTokens { private TestSaml2AuthenticationTokens() { } public static Saml2AuthenticationToken token() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.relyingPartyRegistration() .build(); return new Saml2AuthenticationToken(relyingPartyRegistration, "saml2-xml-response-object"); } }
1,372
34.205128
110
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/Saml2RedirectAuthenticationRequestTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication; import org.junit.jupiter.api.Test; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import org.springframework.util.SerializationUtils; import static org.assertj.core.api.Assertions.assertThat; class Saml2RedirectAuthenticationRequestTests { private static final String IDP_SSO_URL = "https://sso-url.example.com/IDP/SSO"; @Test void serializeWhenDeserializeThenSameFields() { Saml2RedirectAuthenticationRequest authenticationRequest = getAuthenticationRequestBuilder().build(); byte[] bytes = SerializationUtils.serialize(authenticationRequest); Saml2RedirectAuthenticationRequest deserializedAuthenticationRequest = (Saml2RedirectAuthenticationRequest) SerializationUtils .deserialize(bytes); assertThat(deserializedAuthenticationRequest).usingRecursiveComparison().isEqualTo(authenticationRequest); } @Test void serializeWhenDeserializeAndCompareToOtherThenNotSame() { Saml2RedirectAuthenticationRequest authenticationRequest = getAuthenticationRequestBuilder().build(); Saml2RedirectAuthenticationRequest otherAuthenticationRequest = getAuthenticationRequestBuilder() .relayState("relay").build(); byte[] bytes = SerializationUtils.serialize(otherAuthenticationRequest); Saml2RedirectAuthenticationRequest deserializedAuthenticationRequest = (Saml2RedirectAuthenticationRequest) SerializationUtils .deserialize(bytes); assertThat(deserializedAuthenticationRequest).usingRecursiveComparison().isNotEqualTo(authenticationRequest); } private Saml2RedirectAuthenticationRequest.Builder getAuthenticationRequestBuilder() { return Saml2RedirectAuthenticationRequest .withRelyingPartyRegistration(TestRelyingPartyRegistrations.relyingPartyRegistration().build()) .samlRequest("request").authenticationRequestUri(IDP_SSO_URL); } }
2,538
43.54386
128
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/DefaultSaml2AuthenticatedPrincipalTests.java
/* * 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.provider.service.authentication; import java.time.Instant; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; public class DefaultSaml2AuthenticatedPrincipalTests { @Test public void createDefaultSaml2AuthenticatedPrincipal() { Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", attributes); assertThat(principal.getName()).isEqualTo("user"); assertThat(principal.getAttributes()).isEqualTo(attributes); } @Test public void createDefaultSaml2AuthenticatedPrincipalWhenNameNullThenException() { Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); assertThatIllegalArgumentException().isThrownBy(() -> new DefaultSaml2AuthenticatedPrincipal(null, attributes)) .withMessageContaining("name cannot be null"); } @Test public void createDefaultSaml2AuthenticatedPrincipalWhenAttributesNullThenException() { assertThatIllegalArgumentException().isThrownBy(() -> new DefaultSaml2AuthenticatedPrincipal("user", null)) .withMessageContaining("attributes cannot be null"); } @Test public void getFirstAttributeWhenStringValueThenReturnsValue() { Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", attributes); assertThat(principal.<String>getFirstAttribute("email")).isEqualTo(attributes.get("email").get(0)); } @Test public void getAttributeWhenStringValuesThenReturnsValues() { Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("email", Arrays.asList("john.doe@example.com", "doe.john@example.com")); DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", attributes); assertThat(principal.<String>getAttribute("email")).isEqualTo(attributes.get("email")); } @Test public void getAttributeWhenDistinctValuesThenReturnsValues() { final Boolean registered = true; final Instant registeredDate = Instant.parse("1970-01-01T00:00:00Z"); Map<String, List<Object>> attributes = new LinkedHashMap<>(); attributes.put("registration", Arrays.asList(registered, registeredDate)); DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", attributes); List<Object> registrationInfo = principal.getAttribute("registration"); assertThat(registrationInfo).isNotNull(); assertThat((Boolean) registrationInfo.get(0)).isEqualTo(registered); assertThat((Instant) registrationInfo.get(1)).isEqualTo(registeredDate); } }
3,758
43.223529
113
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/TestOpenSamlObjects.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.authentication; import java.security.cert.X509Certificate; import java.time.Instant; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.UUID; import java.util.function.Consumer; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.xml.namespace.QName; import org.apache.xml.security.encryption.XMLCipherParameters; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.core.xml.schema.XSAny; import org.opensaml.core.xml.schema.XSBoolean; import org.opensaml.core.xml.schema.XSBooleanValue; import org.opensaml.core.xml.schema.XSInteger; import org.opensaml.core.xml.schema.XSString; import org.opensaml.core.xml.schema.XSURI; import org.opensaml.core.xml.schema.impl.XSAnyBuilder; import org.opensaml.core.xml.schema.impl.XSBooleanBuilder; import org.opensaml.core.xml.schema.impl.XSIntegerBuilder; import org.opensaml.core.xml.schema.impl.XSStringBuilder; import org.opensaml.core.xml.schema.impl.XSURIBuilder; import org.opensaml.saml.common.SAMLVersion; import org.opensaml.saml.common.SignableSAMLObject; 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.AttributeValue; 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.EncryptedAttribute; 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.Status; import org.opensaml.saml.saml2.core.StatusCode; 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.core.impl.AttributeBuilder; import org.opensaml.saml.saml2.core.impl.AttributeStatementBuilder; import org.opensaml.saml.saml2.core.impl.IssuerBuilder; import org.opensaml.saml.saml2.core.impl.LogoutRequestBuilder; import org.opensaml.saml.saml2.core.impl.LogoutResponseBuilder; import org.opensaml.saml.saml2.core.impl.NameIDBuilder; import org.opensaml.saml.saml2.core.impl.StatusBuilder; import org.opensaml.saml.saml2.core.impl.StatusCodeBuilder; import org.opensaml.saml.saml2.encryption.Encrypter; import org.opensaml.security.SecurityException; import org.opensaml.security.credential.BasicCredential; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.SignatureSigningParameters; import org.opensaml.xmlsec.encryption.support.DataEncryptionParameters; import org.opensaml.xmlsec.encryption.support.EncryptionException; import org.opensaml.xmlsec.encryption.support.KeyEncryptionParameters; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.opensaml.xmlsec.signature.support.SignatureException; import org.opensaml.xmlsec.signature.support.SignatureSupport; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; public final class TestOpenSamlObjects { static { OpenSamlInitializationService.initialize(); } private static String USERNAME = "test@saml.user"; private static String DESTINATION = "https://localhost/login/saml2/sso/idp-alias"; private static String LOGOUT_DESTINATION = "http://localhost/logout/saml2/slo"; public static String RELYING_PARTY_ENTITY_ID = "https://localhost/saml2/service-provider-metadata/idp-alias"; public static String ASSERTING_PARTY_ENTITY_ID = "https://some.idp.test/saml2/idp"; private static SecretKey SECRET_KEY = new SecretKeySpec( Base64.getDecoder().decode("shOnwNMoCv88HKMEa91+FlYoD5RNvzMTAL5LGxZKIFk="), "AES"); private TestOpenSamlObjects() { } public static Response response() { return response(DESTINATION, ASSERTING_PARTY_ENTITY_ID); } public static Response response(String destination, String issuerEntityId) { Response response = build(Response.DEFAULT_ELEMENT_NAME); response.setID("R" + UUID.randomUUID().toString()); response.setVersion(SAMLVersion.VERSION_20); response.setID("_" + UUID.randomUUID().toString()); response.setDestination(destination); response.setIssuer(issuer(issuerEntityId)); return response; } static Response signedResponseWithOneAssertion() { return signedResponseWithOneAssertion((response) -> { }); } static Response signedResponseWithOneAssertion(Consumer<Response> responseConsumer) { Response response = response(); response.getAssertions().add(assertion()); responseConsumer.accept(response); return signed(response, TestSaml2X509Credentials.assertingPartySigningCredential(), RELYING_PARTY_ENTITY_ID); } static Assertion assertion() { return assertion(USERNAME, ASSERTING_PARTY_ENTITY_ID, RELYING_PARTY_ENTITY_ID, DESTINATION); } public static Assertion assertion(String username, String issuerEntityId, String recipientEntityId, String recipientUri) { Assertion assertion = build(Assertion.DEFAULT_ELEMENT_NAME); assertion.setID("A" + UUID.randomUUID().toString()); assertion.setVersion(SAMLVersion.VERSION_20); assertion.setIssuer(issuer(issuerEntityId)); assertion.setSubject(subject(username)); assertion.setConditions(conditions()); assertion.setIssueInstant(Instant.now()); SubjectConfirmation subjectConfirmation = subjectConfirmation(); subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); SubjectConfirmationData confirmationData = subjectConfirmationData(recipientEntityId); confirmationData.setRecipient(recipientUri); subjectConfirmation.setSubjectConfirmationData(confirmationData); assertion.getSubject().getSubjectConfirmations().add(subjectConfirmation); AuthnStatement statement = build(AuthnStatement.DEFAULT_ELEMENT_NAME); statement.setSessionIndex("session-index"); assertion.getAuthnStatements().add(statement); return assertion; } static Issuer issuer(String entityId) { Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(entityId); return issuer; } static Subject subject(String principalName) { Subject subject = build(Subject.DEFAULT_ELEMENT_NAME); if (principalName != null) { subject.setNameID(nameId(principalName)); } return subject; } static NameID nameId(String principalName) { NameID nameId = build(NameID.DEFAULT_ELEMENT_NAME); nameId.setValue(principalName); return nameId; } static SubjectConfirmation subjectConfirmation() { return build(SubjectConfirmation.DEFAULT_ELEMENT_NAME); } static SubjectConfirmationData subjectConfirmationData(String recipient) { SubjectConfirmationData subject = build(SubjectConfirmationData.DEFAULT_ELEMENT_NAME); subject.setRecipient(recipient); return subject; } static Conditions conditions() { return build(Conditions.DEFAULT_ELEMENT_NAME); } public static AuthnRequest authnRequest() { Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(ASSERTING_PARTY_ENTITY_ID); AuthnRequest authnRequest = build(AuthnRequest.DEFAULT_ELEMENT_NAME); authnRequest.setIssuer(issuer); authnRequest.setDestination(ASSERTING_PARTY_ENTITY_ID + "/SSO.saml2"); authnRequest.setAssertionConsumerServiceURL(DESTINATION); return authnRequest; } public static LogoutRequest logoutRequest() { Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(ASSERTING_PARTY_ENTITY_ID); NameID nameId = build(NameID.DEFAULT_ELEMENT_NAME); nameId.setValue("user"); LogoutRequest logoutRequest = build(LogoutRequest.DEFAULT_ELEMENT_NAME); logoutRequest.setIssuer(issuer); logoutRequest.setDestination(LOGOUT_DESTINATION); logoutRequest.setNameID(nameId); return logoutRequest; } static Credential getSigningCredential(Saml2X509Credential credential, String entityId) { BasicCredential cred = getBasicCredential(credential); cred.setEntityId(entityId); cred.setUsageType(UsageType.SIGNING); return cred; } static BasicCredential getBasicCredential(Saml2X509Credential credential) { return CredentialSupport.getSimpleCredential(credential.getCertificate(), credential.getPrivateKey()); } static <T extends SignableSAMLObject> T signed(T signable, Saml2X509Credential credential, String entityId, String signAlgorithmUri) { SignatureSigningParameters parameters = new SignatureSigningParameters(); Credential signingCredential = getSigningCredential(credential, entityId); parameters.setSigningCredential(signingCredential); parameters.setSignatureAlgorithm(signAlgorithmUri); parameters.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA256); parameters.setSignatureCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); try { SignatureSupport.signObject(signable, parameters); } catch (MarshallingException | SignatureException | SecurityException ex) { throw new Saml2Exception(ex); } return signable; } public static <T extends SignableSAMLObject> T signed(T signable, Saml2X509Credential credential, String entityId) { return signed(signable, credential, entityId, SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); } static EncryptedAssertion encrypted(Assertion assertion, Saml2X509Credential credential) { X509Certificate certificate = credential.getCertificate(); Encrypter encrypter = getEncrypter(certificate); try { return encrypter.encrypt(assertion); } catch (EncryptionException ex) { throw new Saml2Exception("Unable to encrypt assertion.", ex); } } static EncryptedID encrypted(NameID nameId, Saml2X509Credential credential) { X509Certificate certificate = credential.getCertificate(); Encrypter encrypter = getEncrypter(certificate); try { return encrypter.encrypt(nameId); } catch (EncryptionException ex) { throw new Saml2Exception("Unable to encrypt nameID.", ex); } } static EncryptedAttribute encrypted(String name, String value, Saml2X509Credential credential) { Attribute attribute = attribute(name, value); X509Certificate certificate = credential.getCertificate(); Encrypter encrypter = getEncrypter(certificate); try { return encrypter.encrypt(attribute); } catch (EncryptionException ex) { throw new Saml2Exception("Unable to encrypt nameID.", ex); } } private static Encrypter getEncrypter(X509Certificate certificate) { String dataAlgorithm = XMLCipherParameters.AES_256; String keyAlgorithm = XMLCipherParameters.RSA_1_5; BasicCredential dataCredential = new BasicCredential(SECRET_KEY); DataEncryptionParameters dataEncryptionParameters = new DataEncryptionParameters(); dataEncryptionParameters.setEncryptionCredential(dataCredential); dataEncryptionParameters.setAlgorithm(dataAlgorithm); Credential credential = CredentialSupport.getSimpleCredential(certificate, null); KeyEncryptionParameters keyEncryptionParameters = new KeyEncryptionParameters(); keyEncryptionParameters.setEncryptionCredential(credential); keyEncryptionParameters.setAlgorithm(keyAlgorithm); Encrypter encrypter = new Encrypter(dataEncryptionParameters, keyEncryptionParameters); Encrypter.KeyPlacement keyPlacement = Encrypter.KeyPlacement.valueOf("PEER"); encrypter.setKeyPlacement(keyPlacement); return encrypter; } static Attribute attribute(String name, String value) { Attribute attribute = build(Attribute.DEFAULT_ELEMENT_NAME); attribute.setName(name); XSString xsValue = new XSStringBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); xsValue.setValue(value); attribute.getAttributeValues().add(xsValue); return attribute; } static AttributeStatement customAttributeStatement(String attributeName, XMLObject customAttributeValue) { AttributeStatementBuilder attributeStatementBuilder = new AttributeStatementBuilder(); AttributeBuilder attributeBuilder = new AttributeBuilder(); Attribute attribute = attributeBuilder.buildObject(); attribute.setName(attributeName); attribute.getAttributeValues().add(customAttributeValue); AttributeStatement attributeStatement = attributeStatementBuilder.buildObject(); attributeStatement.getAttributes().add(attribute); return attributeStatement; } static List<AttributeStatement> attributeStatements() { List<AttributeStatement> attributeStatements = new ArrayList<>(); AttributeStatementBuilder attributeStatementBuilder = new AttributeStatementBuilder(); AttributeBuilder attributeBuilder = new AttributeBuilder(); AttributeStatement attrStmt1 = attributeStatementBuilder.buildObject(); Attribute emailAttr = attributeBuilder.buildObject(); emailAttr.setName("email"); XSAny email1 = new XSAnyBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSAny.TYPE_NAME); // gh-8864 email1.setTextContent("john.doe@example.com"); emailAttr.getAttributeValues().add(email1); XSAny email2 = new XSAnyBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME); email2.setTextContent("doe.john@example.com"); emailAttr.getAttributeValues().add(email2); attrStmt1.getAttributes().add(emailAttr); Attribute nameAttr = attributeBuilder.buildObject(); nameAttr.setName("name"); XSString name = new XSStringBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); name.setValue("John Doe"); nameAttr.getAttributeValues().add(name); attrStmt1.getAttributes().add(nameAttr); Attribute roleOneAttr = attributeBuilder.buildObject(); // gh-11042 roleOneAttr.setName("role"); XSString roleOne = new XSStringBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); roleOne.setValue("RoleOne"); roleOneAttr.getAttributeValues().add(roleOne); attrStmt1.getAttributes().add(roleOneAttr); Attribute roleTwoAttr = attributeBuilder.buildObject(); // gh-11042 roleTwoAttr.setName("role"); XSString roleTwo = new XSStringBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); roleTwo.setValue("RoleTwo"); roleTwoAttr.getAttributeValues().add(roleTwo); attrStmt1.getAttributes().add(roleTwoAttr); Attribute ageAttr = attributeBuilder.buildObject(); ageAttr.setName("age"); XSInteger age = new XSIntegerBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); age.setValue(21); ageAttr.getAttributeValues().add(age); attrStmt1.getAttributes().add(ageAttr); attributeStatements.add(attrStmt1); AttributeStatement attrStmt2 = attributeStatementBuilder.buildObject(); Attribute websiteAttr = attributeBuilder.buildObject(); websiteAttr.setName("website"); XSURI uri = new XSURIBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSURI.TYPE_NAME); uri.setURI("https://johndoe.com/"); websiteAttr.getAttributeValues().add(uri); attrStmt2.getAttributes().add(websiteAttr); Attribute registeredAttr = attributeBuilder.buildObject(); registeredAttr.setName("registered"); XSBoolean registered = new XSBooleanBuilder().buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSBoolean.TYPE_NAME); registered.setValue(new XSBooleanValue(true, false)); registeredAttr.getAttributeValues().add(registered); attrStmt2.getAttributes().add(registeredAttr); attributeStatements.add(attrStmt2); return attributeStatements; } static Status successStatus() { return status(StatusCode.SUCCESS); } static Status status(String code) { Status status = new StatusBuilder().buildObject(); StatusCode statusCode = new StatusCodeBuilder().buildObject(); statusCode.setValue(code); status.setStatusCode(statusCode); return status; } public static LogoutRequest assertingPartyLogoutRequest(RelyingPartyRegistration registration) { LogoutRequestBuilder logoutRequestBuilder = new LogoutRequestBuilder(); LogoutRequest logoutRequest = logoutRequestBuilder.buildObject(); logoutRequest.setID("id"); NameIDBuilder nameIdBuilder = new NameIDBuilder(); NameID nameId = nameIdBuilder.buildObject(); nameId.setValue("user"); logoutRequest.setNameID(nameId); IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject(); issuer.setValue(registration.getAssertingPartyDetails().getEntityId()); logoutRequest.setIssuer(issuer); logoutRequest.setDestination(registration.getSingleLogoutServiceLocation()); return logoutRequest; } public static LogoutRequest assertingPartyLogoutRequestNameIdInEncryptedId(RelyingPartyRegistration registration) { LogoutRequestBuilder logoutRequestBuilder = new LogoutRequestBuilder(); LogoutRequest logoutRequest = logoutRequestBuilder.buildObject(); logoutRequest.setID("id"); NameIDBuilder nameIdBuilder = new NameIDBuilder(); NameID nameId = nameIdBuilder.buildObject(); nameId.setValue("user"); logoutRequest.setNameID(null); Saml2X509Credential credential = registration.getAssertingPartyDetails().getEncryptionX509Credentials() .iterator().next(); EncryptedID encrypted = encrypted(nameId, credential); logoutRequest.setEncryptedID(encrypted); IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject(); issuer.setValue(registration.getAssertingPartyDetails().getEntityId()); logoutRequest.setIssuer(issuer); logoutRequest.setDestination(registration.getSingleLogoutServiceLocation()); return logoutRequest; } public static LogoutResponse assertingPartyLogoutResponse(RelyingPartyRegistration registration) { LogoutResponseBuilder logoutResponseBuilder = new LogoutResponseBuilder(); LogoutResponse logoutResponse = logoutResponseBuilder.buildObject(); logoutResponse.setID("id"); StatusBuilder statusBuilder = new StatusBuilder(); StatusCodeBuilder statusCodeBuilder = new StatusCodeBuilder(); StatusCode code = statusCodeBuilder.buildObject(); code.setValue(StatusCode.SUCCESS); Status status = statusBuilder.buildObject(); status.setStatusCode(code); logoutResponse.setStatus(status); IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject(); issuer.setValue(registration.getAssertingPartyDetails().getEntityId()); logoutResponse.setIssuer(issuer); logoutResponse.setDestination(registration.getSingleLogoutServiceResponseLocation()); return logoutResponse; } public static LogoutRequest relyingPartyLogoutRequest(RelyingPartyRegistration registration) { LogoutRequestBuilder logoutRequestBuilder = new LogoutRequestBuilder(); LogoutRequest logoutRequest = logoutRequestBuilder.buildObject(); logoutRequest.setID("id"); NameIDBuilder nameIdBuilder = new NameIDBuilder(); NameID nameId = nameIdBuilder.buildObject(); nameId.setValue("user"); logoutRequest.setNameID(nameId); IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject(); issuer.setValue(registration.getAssertingPartyDetails().getEntityId()); logoutRequest.setIssuer(issuer); logoutRequest.setDestination(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()); return logoutRequest; } static <T extends XMLObject> T build(QName qName) { return (T) XMLObjectProviderRegistrySupport.getBuilderFactory().getBuilder(qName).buildObject(qName); } }
20,620
42.688559
117
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSamlLogoutRequestValidatorTests.java
/* * 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.logout; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.XMLObject; import org.opensaml.saml.saml2.core.LogoutRequest; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlSigningUtils.QueryParametersPartial; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OpenSamlLogoutRequestValidator} * * @author Josh Cummings */ public class OpenSamlLogoutRequestValidatorTests { private final OpenSamlLogoutRequestValidator manager = new OpenSamlLogoutRequestValidator(); @Test public void handleWhenPostBindingThenValidates() { RelyingPartyRegistration registration = registration().build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); sign(logoutRequest, registration); Saml2LogoutRequest request = post(logoutRequest, registration); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isFalse(); } @Test public void handleWhenNameIdIsEncryptedIdPostThenValidates() { RelyingPartyRegistration registration = decrypting(encrypting(registration())).build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequestNameIdInEncryptedId(registration); sign(logoutRequest, registration); Saml2LogoutRequest request = post(logoutRequest, registration); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).withFailMessage(() -> result.getErrors().toString()).isFalse(); } @Test public void handleWhenRedirectBindingThenValidatesSignatureParameter() { RelyingPartyRegistration registration = registration() .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.REDIRECT)) .build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); Saml2LogoutRequest request = redirect(logoutRequest, registration, OpenSamlSigningUtils.sign(registration)); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isFalse(); } @Test public void handleWhenInvalidIssuerThenInvalidSignatureError() { RelyingPartyRegistration registration = registration().build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); logoutRequest.getIssuer().setValue("wrong"); sign(logoutRequest, registration); Saml2LogoutRequest request = post(logoutRequest, registration); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_SIGNATURE); } @Test public void handleWhenMismatchedUserThenInvalidRequestError() { RelyingPartyRegistration registration = registration().build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); logoutRequest.getNameID().setValue("wrong"); sign(logoutRequest, registration); Saml2LogoutRequest request = post(logoutRequest, registration); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_REQUEST); } @Test public void handleWhenMissingUserThenSubjectNotFoundError() { RelyingPartyRegistration registration = registration().build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); logoutRequest.setNameID(null); sign(logoutRequest, registration); Saml2LogoutRequest request = post(logoutRequest, registration); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.SUBJECT_NOT_FOUND); } @Test public void handleWhenMismatchedDestinationThenInvalidDestinationError() { RelyingPartyRegistration registration = registration().build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); logoutRequest.setDestination("wrong"); sign(logoutRequest, registration); Saml2LogoutRequest request = post(logoutRequest, registration); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_DESTINATION); } // gh-10923 @Test public void handleWhenLogoutResponseHasLineBreaksThenHandles() { RelyingPartyRegistration registration = registration().build(); LogoutRequest logoutRequest = TestOpenSamlObjects.assertingPartyLogoutRequest(registration); sign(logoutRequest, registration); String encoded = new StringBuffer( Saml2Utils.samlEncode(serialize(logoutRequest).getBytes(StandardCharsets.UTF_8))).insert(10, "\r\n") .toString(); Saml2LogoutRequest request = Saml2LogoutRequest.withRelyingPartyRegistration(registration).samlRequest(encoded) .build(); Saml2LogoutRequestValidatorParameters parameters = new Saml2LogoutRequestValidatorParameters(request, registration, authentication(registration)); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isFalse(); } private RelyingPartyRegistration.Builder registration() { return signing(verifying(TestRelyingPartyRegistrations.noCredentials())) .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)); } private RelyingPartyRegistration.Builder decrypting(RelyingPartyRegistration.Builder builder) { return builder .decryptionX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyDecryptingCredential())); } private RelyingPartyRegistration.Builder encrypting(RelyingPartyRegistration.Builder builder) { return builder.assertingPartyDetails((party) -> party.encryptionX509Credentials( (c) -> c.add(TestSaml2X509Credentials.assertingPartyEncryptingCredential()))); } private RelyingPartyRegistration.Builder verifying(RelyingPartyRegistration.Builder builder) { return builder.assertingPartyDetails((party) -> party .verificationX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))); } private RelyingPartyRegistration.Builder signing(RelyingPartyRegistration.Builder builder) { return builder.signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartySigningCredential())); } private Authentication authentication(RelyingPartyRegistration registration) { DefaultSaml2AuthenticatedPrincipal principal = new DefaultSaml2AuthenticatedPrincipal("user", new HashMap<>()); principal.setRelyingPartyRegistrationId(registration.getRegistrationId()); return new Saml2Authentication(principal, "response", new ArrayList<>()); } private Saml2LogoutRequest post(LogoutRequest logoutRequest, RelyingPartyRegistration registration) { return Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest(Saml2Utils.samlEncode(serialize(logoutRequest).getBytes(StandardCharsets.UTF_8))).build(); } private Saml2LogoutRequest redirect(LogoutRequest logoutRequest, RelyingPartyRegistration registration, QueryParametersPartial partial) { String serialized = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(serialize(logoutRequest))); Map<String, String> parameters = partial.param(Saml2ParameterNames.SAML_REQUEST, serialized).parameters(); return Saml2LogoutRequest.withRelyingPartyRegistration(registration).samlRequest(serialized) .parameters((params) -> params.putAll(parameters)).build(); } private void sign(LogoutRequest logoutRequest, RelyingPartyRegistration registration) { TestOpenSamlObjects.signed(logoutRequest, registration.getSigningX509Credentials().iterator().next(), registration.getAssertingPartyDetails().getEntityId()); } private String serialize(XMLObject object) { return OpenSamlSigningUtils.serialize(object); } }
10,888
49.412037
125
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSamlSigningUtils.java
/* * 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.logout; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.Marshaller; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; import org.opensaml.security.SecurityException; import org.opensaml.security.credential.BasicCredential; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.SignatureSigningParameters; import org.opensaml.xmlsec.SignatureSigningParametersResolver; import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; import org.opensaml.xmlsec.crypto.XMLSigningUtil; import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; import org.opensaml.xmlsec.signature.SignableXMLObject; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.opensaml.xmlsec.signature.support.SignatureSupport; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * Utility methods for signing SAML components with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlSigningUtils { static String serialize(XMLObject object) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } static <O extends SignableXMLObject> O sign(O object, RelyingPartyRegistration relyingPartyRegistration) { SignatureSigningParameters parameters = resolveSigningParameters(relyingPartyRegistration); try { SignatureSupport.signObject(object, parameters); return object; } catch (Exception ex) { throw new Saml2Exception(ex); } } static QueryParametersPartial sign(RelyingPartyRegistration registration) { return new QueryParametersPartial(registration); } private static SignatureSigningParameters resolveSigningParameters( RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = resolveSigningCredentials(relyingPartyRegistration); List<String> algorithms = relyingPartyRegistration.getAssertingPartyDetails().getSigningAlgorithms(); List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); CriteriaSet criteria = new CriteriaSet(); BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); signingConfiguration.setSigningCredentials(credentials); signingConfiguration.setSignatureAlgorithms(algorithms); signingConfiguration.setSignatureReferenceDigestMethods(digests); signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); criteria.add(new SignatureSigningConfigurationCriterion(signingConfiguration)); try { SignatureSigningParameters parameters = resolver.resolveSingle(criteria); Assert.notNull(parameters, "Failed to resolve any signing credential"); return parameters; } catch (Exception ex) { throw new Saml2Exception(ex); } } private static NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); namedManager.setUseDefaultManager(true); final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); // Generator for X509Credentials final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); x509Factory.setEmitEntityCertificate(true); x509Factory.setEmitEntityCertificateChain(true); defaultManager.registerFactory(x509Factory); return namedManager; } private static List<Credential> resolveSigningCredentials(RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = new ArrayList<>(); for (Saml2X509Credential x509Credential : relyingPartyRegistration.getSigningX509Credentials()) { X509Certificate certificate = x509Credential.getCertificate(); PrivateKey privateKey = x509Credential.getPrivateKey(); BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); credential.setEntityId(relyingPartyRegistration.getEntityId()); credential.setUsageType(UsageType.SIGNING); credentials.add(credential); } return credentials; } private OpenSamlSigningUtils() { } static class QueryParametersPartial { final RelyingPartyRegistration registration; final Map<String, String> components = new LinkedHashMap<>(); QueryParametersPartial(RelyingPartyRegistration registration) { this.registration = registration; } QueryParametersPartial param(String key, String value) { this.components.put(key, value); return this; } Map<String, String> parameters() { SignatureSigningParameters parameters = resolveSigningParameters(this.registration); Credential credential = parameters.getSigningCredential(); String algorithmUri = parameters.getSignatureAlgorithm(); this.components.put(Saml2ParameterNames.SIG_ALG, algorithmUri); UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); for (Map.Entry<String, String> component : this.components.entrySet()) { builder.queryParam(component.getKey(), UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); } String queryString = builder.build(true).toString().substring(1); try { byte[] rawSignature = XMLSigningUtil.signWithURI(credential, algorithmUri, queryString.getBytes(StandardCharsets.UTF_8)); String b64Signature = Saml2Utils.samlEncode(rawSignature); this.components.put(Saml2ParameterNames.SIGNATURE, b64Signature); } catch (SecurityException ex) { throw new Saml2Exception(ex); } return this.components; } } }
7,943
39.738462
111
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/authentication/logout/OpenSamlLogoutResponseValidatorTests.java
/* * 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.logout; import java.nio.charset.StandardCharsets; import java.util.Map; import org.junit.jupiter.api.Test; import org.opensaml.core.xml.XMLObject; import org.opensaml.saml.saml2.core.LogoutResponse; import org.opensaml.saml.saml2.core.StatusCode; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.authentication.TestOpenSamlObjects; import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlSigningUtils.QueryParametersPartial; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OpenSamlLogoutResponseValidator} * * @author Josh Cummings */ public class OpenSamlLogoutResponseValidatorTests { private final OpenSamlLogoutResponseValidator manager = new OpenSamlLogoutResponseValidator(); @Test public void handleWhenAuthenticatedThenHandles() { RelyingPartyRegistration registration = signing(verifying(registration())).build(); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).id("id") .build(); LogoutResponse logoutResponse = TestOpenSamlObjects.assertingPartyLogoutResponse(registration); sign(logoutResponse, registration); Saml2LogoutResponse response = post(logoutResponse, registration); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(response, logoutRequest, registration); this.manager.validate(parameters); } @Test public void handleWhenRedirectBindingThenValidatesSignatureParameter() { RelyingPartyRegistration registration = signing(verifying(registration())) .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.REDIRECT)) .build(); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).id("id") .build(); LogoutResponse logoutResponse = TestOpenSamlObjects.assertingPartyLogoutResponse(registration); Saml2LogoutResponse response = redirect(logoutResponse, registration, OpenSamlSigningUtils.sign(registration)); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(response, logoutRequest, registration); this.manager.validate(parameters); } @Test public void handleWhenInvalidIssuerThenInvalidSignatureError() { RelyingPartyRegistration registration = registration().build(); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).id("id") .build(); LogoutResponse logoutResponse = TestOpenSamlObjects.assertingPartyLogoutResponse(registration); logoutResponse.getIssuer().setValue("wrong"); sign(logoutResponse, registration); Saml2LogoutResponse response = post(logoutResponse, registration); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(response, logoutRequest, registration); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_SIGNATURE); } @Test public void handleWhenMismatchedDestinationThenInvalidDestinationError() { RelyingPartyRegistration registration = registration().build(); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).id("id") .build(); LogoutResponse logoutResponse = TestOpenSamlObjects.assertingPartyLogoutResponse(registration); logoutResponse.setDestination("wrong"); sign(logoutResponse, registration); Saml2LogoutResponse response = post(logoutResponse, registration); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(response, logoutRequest, registration); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_DESTINATION); } @Test public void handleWhenStatusNotSuccessThenInvalidResponseError() { RelyingPartyRegistration registration = registration().build(); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).id("id") .build(); LogoutResponse logoutResponse = TestOpenSamlObjects.assertingPartyLogoutResponse(registration); logoutResponse.getStatus().getStatusCode().setValue(StatusCode.UNKNOWN_PRINCIPAL); sign(logoutResponse, registration); Saml2LogoutResponse response = post(logoutResponse, registration); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(response, logoutRequest, registration); Saml2LogoutValidatorResult result = this.manager.validate(parameters); assertThat(result.hasErrors()).isTrue(); assertThat(result.getErrors().iterator().next().getErrorCode()).isEqualTo(Saml2ErrorCodes.INVALID_RESPONSE); } // gh-10923 @Test public void handleWhenLogoutResponseHasLineBreaksThenHandles() { RelyingPartyRegistration registration = signing(verifying(registration())).build(); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration).id("id") .build(); LogoutResponse logoutResponse = TestOpenSamlObjects.assertingPartyLogoutResponse(registration); sign(logoutResponse, registration); String encoded = new StringBuilder( Saml2Utils.samlEncode(serialize(logoutResponse).getBytes(StandardCharsets.UTF_8))).insert(10, "\r\n") .toString(); Saml2LogoutResponse response = Saml2LogoutResponse.withRelyingPartyRegistration(registration) .samlResponse(encoded).build(); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(response, logoutRequest, registration); this.manager.validate(parameters); } private RelyingPartyRegistration.Builder registration() { return signing(verifying(TestRelyingPartyRegistrations.noCredentials())) .assertingPartyDetails((party) -> party.singleLogoutServiceBinding(Saml2MessageBinding.POST)); } private RelyingPartyRegistration.Builder verifying(RelyingPartyRegistration.Builder builder) { return builder.assertingPartyDetails((party) -> party .verificationX509Credentials((c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))); } private RelyingPartyRegistration.Builder signing(RelyingPartyRegistration.Builder builder) { return builder.signingX509Credentials((c) -> c.add(TestSaml2X509Credentials.assertingPartySigningCredential())); } private Saml2LogoutResponse post(LogoutResponse logoutResponse, RelyingPartyRegistration registration) { return Saml2LogoutResponse.withRelyingPartyRegistration(registration) .samlResponse(Saml2Utils.samlEncode(serialize(logoutResponse).getBytes(StandardCharsets.UTF_8))) .build(); } private Saml2LogoutResponse redirect(LogoutResponse logoutResponse, RelyingPartyRegistration registration, QueryParametersPartial partial) { String serialized = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(serialize(logoutResponse))); Map<String, String> parameters = partial.param(Saml2ParameterNames.SAML_RESPONSE, serialized).parameters(); return Saml2LogoutResponse.withRelyingPartyRegistration(registration).samlResponse(serialized) .parameters((params) -> params.putAll(parameters)).build(); } private void sign(LogoutResponse logoutResponse, RelyingPartyRegistration registration) { TestOpenSamlObjects.signed(logoutResponse, registration.getSigningX509Credentials().iterator().next(), registration.getAssertingPartyDetails().getEntityId()); } private String serialize(XMLObject object) { return OpenSamlSigningUtils.serialize(object); } }
8,912
49.073034
125
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/RequestMatcherMetadataResponseResolverTests.java
/* * 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.metadata; import java.util.Collection; 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.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.saml2.Saml2Exception; 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.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) public final class RequestMatcherMetadataResponseResolverTests { @Mock Saml2MetadataResolver metadataFactory; @Test void saml2MetadataRegistrationIdResolveWhenMatchesThenResolves() { RelyingPartyRegistration registration = TestRelyingPartyRegistrations.relyingPartyRegistration().build(); RelyingPartyRegistrationRepository registrations = new InMemoryRelyingPartyRegistrationRepository(registration); RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory); String registrationId = registration.getRegistrationId(); given(this.metadataFactory.resolve(any(Collection.class))).willReturn("metadata"); MockHttpServletRequest request = get("/saml2/metadata/" + registrationId); Saml2MetadataResponse response = resolver.resolve(request); assertThat(response.getMetadata()).isEqualTo("metadata"); assertThat(response.getFileName()).isEqualTo("saml-" + registrationId + "-metadata.xml"); verify(this.metadataFactory).resolve(any(Collection.class)); } @Test void saml2MetadataResolveWhenNoMatchingRegistrationThenNull() { RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class); RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory); MockHttpServletRequest request = get("/saml2/metadata"); Saml2MetadataResponse response = resolver.resolve(request); assertThat(response).isNull(); } @Test void saml2MetadataRegistrationIdResolveWhenNoMatchingRegistrationThenException() { RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class); RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory); MockHttpServletRequest request = get("/saml2/metadata/id"); assertThatExceptionOfType(Saml2Exception.class).isThrownBy(() -> resolver.resolve(request)); } @Test void resolveWhenNoRegistrationIdThenResolvesAll() { RelyingPartyRegistration one = withEntityId("one"); RelyingPartyRegistration two = withEntityId("two"); RelyingPartyRegistrationRepository registrations = new InMemoryRelyingPartyRegistrationRepository(one, two); RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory); given(this.metadataFactory.resolve(any(Collection.class))).willReturn("metadata"); MockHttpServletRequest request = get("/saml2/metadata"); Saml2MetadataResponse response = resolver.resolve(request); assertThat(response.getMetadata()).isEqualTo("metadata"); assertThat(response.getFileName()).doesNotContain(one.getRegistrationId()).contains("saml") .contains("metadata.xml"); verify(this.metadataFactory).resolve(any(Collection.class)); } @Test void resolveWhenRequestDoesNotMatchThenNull() { RelyingPartyRegistrationRepository registrations = mock(RelyingPartyRegistrationRepository.class); RequestMatcherMetadataResponseResolver resolver = new RequestMatcherMetadataResponseResolver(registrations, this.metadataFactory); assertThat(resolver.resolve(new MockHttpServletRequest())).isNull(); } private MockHttpServletRequest get(String uri) { MockHttpServletRequest request = new MockHttpServletRequest("GET", uri); request.setServletPath(uri); return request; } private RelyingPartyRegistration withEntityId(String entityId) { return TestRelyingPartyRegistrations.relyingPartyRegistration().registrationId(entityId).entityId(entityId) .build(); } }
5,400
45.560345
115
java
null
spring-security-main/saml2/saml2-service-provider/src/test/java/org/springframework/security/saml2/provider/service/metadata/OpenSamlMetadataResolverTests.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.metadata; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.security.saml2.core.TestSaml2X509Credentials; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.registration.TestRelyingPartyRegistrations; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link OpenSamlMetadataResolver} */ public class OpenSamlMetadataResolverTests { @Test public void resolveWhenRelyingPartyThenMetadataMatches() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full() .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); assertThat(metadata).contains("<md:EntityDescriptor").contains("entityID=\"rp-entity-id\"") .contains("<md:KeyDescriptor use=\"signing\">").contains("<md:KeyDescriptor use=\"encryption\">") .contains("<ds:X509Certificate>MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBh") .contains("Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\"") .contains("Location=\"https://rp.example.org/acs\" index=\"1\"") .contains("ResponseLocation=\"https://rp.example.org/logout/saml2/response\""); } @Test public void resolveWhenRelyingPartyNoCredentialsThenMetadataMatches() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.noCredentials() .assertingPartyDetails((party) -> party.verificationX509Credentials( (c) -> c.add(TestSaml2X509Credentials.relyingPartyVerifyingCredential()))) .build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); assertThat(metadata).contains("<md:EntityDescriptor").contains("entityID=\"rp-entity-id\"") .doesNotContain("<md:KeyDescriptor use=\"signing\">") .doesNotContain("<md:KeyDescriptor use=\"encryption\">") .contains("Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"") .contains("Location=\"https://rp.example.org/acs\" index=\"1\"") .contains("ResponseLocation=\"https://rp.example.org/logout/saml2/response\""); } @Test public void resolveWhenRelyingPartyNameIDFormatThenMetadataMatches() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full().nameIdFormat("format") .build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); assertThat(metadata).contains("<md:NameIDFormat>format</md:NameIDFormat>"); } @Test public void resolveWhenRelyingPartyNoLogoutThenMetadataMatches() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full() .singleLogoutServiceLocation(null).nameIdFormat("format").build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); assertThat(metadata).doesNotContain("ResponseLocation"); } @Test public void resolveWhenEntityDescriptorCustomizerThenUses() { RelyingPartyRegistration relyingPartyRegistration = TestRelyingPartyRegistrations.full() .entityId("originalEntityId").build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); openSamlMetadataResolver.setEntityDescriptorCustomizer( (parameters) -> parameters.getEntityDescriptor().setEntityID("overriddenEntityId")); String metadata = openSamlMetadataResolver.resolve(relyingPartyRegistration); assertThat(metadata).contains("<md:EntityDescriptor").contains("entityID=\"overriddenEntityId\""); } @Test public void resolveIterableWhenRelyingPartiesThenMetadataMatches() { RelyingPartyRegistration one = TestRelyingPartyRegistrations.full() .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); RelyingPartyRegistration two = TestRelyingPartyRegistrations.full().entityId("two") .assertionConsumerServiceBinding(Saml2MessageBinding.REDIRECT).build(); OpenSamlMetadataResolver openSamlMetadataResolver = new OpenSamlMetadataResolver(); String metadata = openSamlMetadataResolver.resolve(List.of(one, two)); assertThat(metadata).contains("<md:EntitiesDescriptor").contains("<md:EntityDescriptor") .contains("entityID=\"rp-entity-id\"").contains("entityID=\"two\"") .contains("<md:KeyDescriptor use=\"signing\">").contains("<md:KeyDescriptor use=\"encryption\">") .contains("<ds:X509Certificate>MIICgTCCAeoCCQCuVzyqFgMSyDANBgkqhkiG9w0BAQsFADCBhDELMAkGA1UEBh") .contains("Binding=\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect\"") .contains("Location=\"https://rp.example.org/acs\" index=\"1\"") .contains("ResponseLocation=\"https://rp.example.org/logout/saml2/response\""); } }
5,865
51.375
113
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/Saml2Exception.java
/* * 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.saml2; /** * @since 5.2 */ public class Saml2Exception extends RuntimeException { public Saml2Exception(String message) { super(message); } public Saml2Exception(String message, Throwable cause) { super(message, cause); } public Saml2Exception(Throwable cause) { super(cause); } }
960
24.972973
75
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2Error.java
/* * 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.io.Serializable; import org.springframework.security.core.SpringSecurityCoreVersion; import org.springframework.util.Assert; /** * A representation of an SAML 2.0 Error. * * <p> * At a minimum, an error response will contain an error code. The commonly used error * code are defined in this class or a new codes can be defined in the future as arbitrary * strings. * </p> * * @since 5.2 */ public class Saml2Error implements Serializable { private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID; private final String errorCode; private final String description; /** * Constructs a {@code Saml2Error} using the provided parameters. * @param errorCode the error code * @param description the error description */ public Saml2Error(String errorCode, String description) { Assert.hasText(errorCode, "errorCode cannot be empty"); this.errorCode = errorCode; this.description = description; } /** * Returns the error code. * @return the error code */ public final String getErrorCode() { return this.errorCode; } /** * Returns the error description. * @return the error description */ public final String getDescription() { return this.description; } @Override public String toString() { return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : ""); } }
2,079
26.368421
107
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2ErrorCodes.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.core; /** * A list of SAML known 2 error codes used during SAML authentication. * * @since 5.2 */ public final class Saml2ErrorCodes { /** * SAML Data does not represent a SAML 2 Response object. A valid XML object was * received, but that object was not a SAML 2 Response object of type * {@code ResponseType} per specification * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=46 */ public static final String UNKNOWN_RESPONSE_CLASS = "unknown_response_class"; /** * The serialized AuthNRequest could not be deserialized correctly. * * @since 5.7 */ public static final String MALFORMED_REQUEST_DATA = "malformed_request_data"; /** * The response data is malformed or incomplete. An invalid XML object was received, * and XML unmarshalling failed. */ public static final String MALFORMED_RESPONSE_DATA = "malformed_response_data"; /** * Request is invalid in a general way. * * @since 5.6 */ public static final String INVALID_REQUEST = "invalid_request"; /** * Response is invalid in a general way. * * @since 5.5 */ public static final String INVALID_RESPONSE = "invalid_response"; /** * Response destination does not match the request URL. A SAML 2 response object was * received at a URL that did not match the URL stored in the {code Destination} * attribute in the Response object. * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=38 */ public static final String INVALID_DESTINATION = "invalid_destination"; /** * The assertion was not valid. The assertion used for authentication failed * validation. Details around the failure will be present in the error description. */ public static final String INVALID_ASSERTION = "invalid_assertion"; /** * The signature of response or assertion was invalid. Either the response or the * assertion was missing a signature or the signature could not be verified using the * system's configured credentials. Most commonly the IDP's X509 certificate. */ public static final String INVALID_SIGNATURE = "invalid_signature"; /** * The assertion did not contain a subject element. The subject element, type * SubjectType, contains a {@code NameID} or an {@code EncryptedID} that is used to * assign the authenticated principal an identifier, typically a username. * * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=18 */ public static final String SUBJECT_NOT_FOUND = "subject_not_found"; /** * The subject did not contain a user identifier The assertion contained a subject * element, but the subject element did not have a {@code NameID} or * {@code EncryptedID} element * * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=18 */ public static final String USERNAME_NOT_FOUND = "username_not_found"; /** * The system failed to decrypt an assertion or a name identifier. This error code * will be thrown if the decryption of either a {@code EncryptedAssertion} or * {@code EncryptedID} fails. * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=17 */ public static final String DECRYPTION_ERROR = "decryption_error"; /** * An Issuer element contained a value that didn't * https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf#page=15 */ public static final String INVALID_ISSUER = "invalid_issuer"; /** * An error happened during validation. Used when internal, non classified, errors are * caught during the authentication process. */ public static final String INTERNAL_VALIDATION_ERROR = "internal_validation_error"; /** * The relying party registration was not found. The registration ID did not * correspond to any relying party registration. */ public static final String RELYING_PARTY_REGISTRATION_NOT_FOUND = "relying_party_registration_not_found"; /** * The InResponseTo content of the response does not match the ID of the AuthNRequest. * * @since 5.7 */ public static final String INVALID_IN_RESPONSE_TO = "invalid_in_response_to"; private Saml2ErrorCodes() { } }
4,802
34.058394
106
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/OpenSamlInitializationService.java
/* * 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.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import javax.xml.XMLConstants; import net.shibboleth.utilities.java.support.xml.BasicParserPool; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.config.InitializationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.springframework.security.saml2.Saml2Exception; /** * An initialization service for initializing OpenSAML. Each Spring Security * OpenSAML-based component invokes the {@link #initialize()} method at static * initialization time. * * {@link #initialize()} is idempotent and may be safely called in custom classes that * need OpenSAML to be initialized in order to function correctly. It's recommended that * you call this {@link #initialize()} method when using Spring Security and OpenSAML * instead of OpenSAML's {@link InitializationService#initialize()}. * * The primary purpose of {@link #initialize()} is to prepare OpenSAML's * {@link XMLObjectProviderRegistry} with some reasonable defaults. Any changes that * Spring Security makes to the registry happen in this method. * * To override those defaults, call {@link #requireInitialize(Consumer)} and change the * registry: * * <pre> * static { * OpenSamlInitializationService.requireInitialize((registry) -&gt; { * registry.setParserPool(...); * registry.getBuilderFactory().registerBuilder(...); * }); * } * </pre> * * {@link #requireInitialize(Consumer)} may only be called once per application. * * If the application already initialized OpenSAML before * {@link #requireInitialize(Consumer)} was called, then the configuration changes will * not be applied and an exception will be thrown. The reason for this is to alert you to * the fact that there are likely some initialization ordering problems in your * application that would otherwise lead to an unpredictable state. * * If you must change the registry's configuration in multiple places in your application, * you are expected to handle the initialization ordering issues yourself instead of * trying to call {@link #requireInitialize(Consumer)} multiple times. * * @author Josh Cummings * @since 5.4 */ public final class OpenSamlInitializationService { private static final Log log = LogFactory.getLog(OpenSamlInitializationService.class); private static final AtomicBoolean initialized = new AtomicBoolean(false); private OpenSamlInitializationService() { } /** * Ready OpenSAML for use and configure it with reasonable defaults. * * Initialization is guaranteed to happen only once per application. This method will * passively return {@code false} if initialization already took place earlier in the * application. * @return whether or not initialization was performed. The first thread to initialize * OpenSAML will return {@code true} while the rest will return {@code false}. * @throws Saml2Exception if OpenSAML failed to initialize */ public static boolean initialize() { return initialize((registry) -> { }); } /** * Ready OpenSAML for use, configure it with reasonable defaults, and modify the * {@link XMLObjectProviderRegistry} using the provided {@link Consumer}. * * Initialization is guaranteed to happen only once per application. This method will * throw an exception if initialization already took place earlier in the application. * @param registryConsumer the {@link Consumer} to further configure the * {@link XMLObjectProviderRegistry} * @throws Saml2Exception if initialization already happened previously or if OpenSAML * failed to initialize */ public static void requireInitialize(Consumer<XMLObjectProviderRegistry> registryConsumer) { if (!initialize(registryConsumer)) { throw new Saml2Exception("OpenSAML was already initialized previously"); } } private static boolean initialize(Consumer<XMLObjectProviderRegistry> registryConsumer) { if (initialized.compareAndSet(false, true)) { log.trace("Initializing OpenSAML"); try { InitializationService.initialize(); } catch (Exception ex) { throw new Saml2Exception(ex); } BasicParserPool parserPool = new BasicParserPool(); parserPool.setMaxPoolSize(50); parserPool.setBuilderFeatures(getParserBuilderFeatures()); try { parserPool.initialize(); } catch (Exception ex) { throw new Saml2Exception(ex); } XMLObjectProviderRegistrySupport.setParserPool(parserPool); registryConsumer.accept(ConfigurationService.get(XMLObjectProviderRegistry.class)); log.debug("Initialized OpenSAML"); return true; } log.debug("Refused to re-initialize OpenSAML"); return false; } private static Map<String, Boolean> getParserBuilderFeatures() { Map<String, Boolean> parserBuilderFeatures = new HashMap<>(); parserBuilderFeatures.put("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE); parserBuilderFeatures.put(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); parserBuilderFeatures.put("http://xml.org/sax/features/external-general-entities", Boolean.FALSE); parserBuilderFeatures.put("http://apache.org/xml/features/validation/schema/normalized-value", Boolean.FALSE); parserBuilderFeatures.put("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE); parserBuilderFeatures.put("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE); return parserBuilderFeatures; } }
6,366
39.55414
112
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2ResponseValidatorResult.java
/* * 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.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.springframework.util.Assert; /** * A result emitted from a SAML 2.0 Response validation attempt * * @author Josh Cummings * @since 5.4 */ public final class Saml2ResponseValidatorResult { static final Saml2ResponseValidatorResult NO_ERRORS = new Saml2ResponseValidatorResult(Collections.emptyList()); private final Collection<Saml2Error> errors; private Saml2ResponseValidatorResult(Collection<Saml2Error> errors) { Assert.notNull(errors, "errors cannot be null"); this.errors = new ArrayList<>(errors); } /** * Say whether this result indicates success * @return whether this result has errors */ public boolean hasErrors() { return !this.errors.isEmpty(); } /** * Return error details regarding the validation attempt * @return the collection of results in this result, if any; returns an empty list * otherwise */ public Collection<Saml2Error> getErrors() { return Collections.unmodifiableCollection(this.errors); } /** * Return a new {@link Saml2ResponseValidatorResult} that contains both the given * {@link Saml2Error} and the errors from the result * @param error the {@link Saml2Error} to append * @return a new {@link Saml2ResponseValidatorResult} for further reporting */ public Saml2ResponseValidatorResult concat(Saml2Error error) { Assert.notNull(error, "error cannot be null"); Collection<Saml2Error> errors = new ArrayList<>(this.errors); errors.add(error); return failure(errors); } /** * Return a new {@link Saml2ResponseValidatorResult} that contains the errors from the * given {@link Saml2ResponseValidatorResult} as well as this result. * @param result the {@link Saml2ResponseValidatorResult} to merge with this one * @return a new {@link Saml2ResponseValidatorResult} for further reporting */ public Saml2ResponseValidatorResult concat(Saml2ResponseValidatorResult result) { Assert.notNull(result, "result cannot be null"); Collection<Saml2Error> errors = new ArrayList<>(this.errors); errors.addAll(result.getErrors()); return failure(errors); } /** * Construct a successful {@link Saml2ResponseValidatorResult} * @return an {@link Saml2ResponseValidatorResult} with no errors */ public static Saml2ResponseValidatorResult success() { return NO_ERRORS; } /** * Construct a failure {@link Saml2ResponseValidatorResult} with the provided detail * @param errors the list of errors * @return an {@link Saml2ResponseValidatorResult} with the errors specified */ public static Saml2ResponseValidatorResult failure(Saml2Error... errors) { return failure(Arrays.asList(errors)); } /** * Construct a failure {@link Saml2ResponseValidatorResult} with the provided detail * @param errors the list of errors * @return an {@link Saml2ResponseValidatorResult} with the errors specified */ public static Saml2ResponseValidatorResult failure(Collection<Saml2Error> errors) { if (errors.isEmpty()) { return NO_ERRORS; } return new Saml2ResponseValidatorResult(errors); } }
3,813
31.598291
113
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2ParameterNames.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.core; /** * Standard parameter names defined in the SAML 2.0 Specification and used by the * Authentication Request, Assertion Consumer Response, Logout Request, and Logout * Response endpoints. * * @author Josh Cummings * @since 5.6 * @see <a target="_blank" href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf">SAML 2.0 * Bindings</a> */ public final class Saml2ParameterNames { /** * {@code SAMLRequest} - used to request authentication or request logout */ public static final String SAML_REQUEST = "SAMLRequest"; /** * {@code SAMLResponse} - used to respond to an authentication or logout request */ public static final String SAML_RESPONSE = "SAMLResponse"; /** * {@code RelayState} - used to communicate shared state between the relying and * asserting party * @see <a target="_blank" href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf#page=8">3.1.1 * Use of RelayState</a> */ public static final String RELAY_STATE = "RelayState"; /** * {@code SigAlg} - used to communicate which signature algorithm to use to verify * signature */ public static final String SIG_ALG = "SigAlg"; /** * {@code Signature} - used to supply cryptographic signature on any SAML 2.0 payload */ public static final String SIGNATURE = "Signature"; private Saml2ParameterNames() { } }
2,052
30.106061
90
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/core/Saml2X509Credential.java
/* * 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.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; import org.springframework.util.Assert; /** * An object for holding a public certificate, any associated private key, and its * intended <a href= * "https://www.oasis-open.org/committees/download.php/8958/sstc-saml-implementation-guidelines-draft-01.pdf"> * usages </a> (Line 584, Section 4.3 Credentials). * * @author Filip Hanik * @author Josh Cummings * @since 5.4 */ public final class Saml2X509Credential { private final PrivateKey privateKey; private final X509Certificate certificate; private final Set<Saml2X509CredentialType> credentialTypes; /** * Creates a {@link Saml2X509Credential} using the provided parameters * @param certificate the credential's public certificiate * @param types the credential's intended usages, must be one of * {@link Saml2X509CredentialType#VERIFICATION} or * {@link Saml2X509CredentialType#ENCRYPTION} or both. */ public Saml2X509Credential(X509Certificate certificate, Saml2X509CredentialType... types) { this(null, false, certificate, types); validateUsages(types, Saml2X509CredentialType.VERIFICATION, Saml2X509CredentialType.ENCRYPTION); } /** * Creates a {@link Saml2X509Credential} using the provided parameters * @param privateKey the credential's private key * @param certificate the credential's public certificate * @param types the credential's intended usages, must be one of * {@link Saml2X509CredentialType#SIGNING} or * {@link Saml2X509CredentialType#DECRYPTION} or both. */ public Saml2X509Credential(PrivateKey privateKey, X509Certificate certificate, Saml2X509CredentialType... types) { this(privateKey, true, certificate, types); validateUsages(types, Saml2X509CredentialType.SIGNING, Saml2X509CredentialType.DECRYPTION); } /** * Creates a {@link Saml2X509Credential} using the provided parameters * @param privateKey the credential's private key * @param certificate the credential's public certificate * @param types the credential's intended usages */ public Saml2X509Credential(PrivateKey privateKey, X509Certificate certificate, Set<Saml2X509CredentialType> types) { Assert.notNull(certificate, "certificate cannot be null"); Assert.notNull(types, "credentialTypes cannot be null"); this.privateKey = privateKey; this.certificate = certificate; this.credentialTypes = types; } /** * Create a {@link Saml2X509Credential} that can be used for encryption. * @param certificate the certificate to use for encryption * @return an encrypting {@link Saml2X509Credential} */ public static Saml2X509Credential encryption(X509Certificate certificate) { return new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION); } /** * Create a {@link Saml2X509Credential} that can be used for verification. * @param certificate the certificate to use for verification * @return a verifying {@link Saml2X509Credential} */ public static Saml2X509Credential verification(X509Certificate certificate) { return new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); } /** * Create a {@link Saml2X509Credential} that can be used for decryption. * @param privateKey the private key to use for decryption * @param certificate the certificate to use for decryption * @return an decrypting {@link Saml2X509Credential} */ public static Saml2X509Credential decryption(PrivateKey privateKey, X509Certificate certificate) { return new Saml2X509Credential(privateKey, certificate, Saml2X509Credential.Saml2X509CredentialType.DECRYPTION); } /** * Create a {@link Saml2X509Credential} that can be used for signing. * @param privateKey the private key to use for signing * @param certificate the certificate to use for signing * @return a signing {@link Saml2X509Credential} */ public static Saml2X509Credential signing(PrivateKey privateKey, X509Certificate certificate) { return new Saml2X509Credential(privateKey, certificate, Saml2X509Credential.Saml2X509CredentialType.SIGNING); } private Saml2X509Credential(PrivateKey privateKey, boolean keyRequired, X509Certificate certificate, Saml2X509CredentialType... types) { Assert.notNull(certificate, "certificate cannot be null"); Assert.notEmpty(types, "credentials types cannot be empty"); if (keyRequired) { Assert.notNull(privateKey, "privateKey cannot be null"); } this.privateKey = privateKey; this.certificate = certificate; this.credentialTypes = new LinkedHashSet<>(Arrays.asList(types)); } /** * Get the private key for this credential * @return the private key, may be null * @see #Saml2X509Credential(PrivateKey, X509Certificate, Saml2X509CredentialType...) */ public PrivateKey getPrivateKey() { return this.privateKey; } /** * Get the public certificate for this credential * @return the public certificate */ public X509Certificate getCertificate() { return this.certificate; } /** * Indicate whether this credential can be used for signing * @return true if the credential has a {@link Saml2X509CredentialType#SIGNING} type */ public boolean isSigningCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.SIGNING); } /** * Indicate whether this credential can be used for decryption * @return true if the credential has a {@link Saml2X509CredentialType#DECRYPTION} * type */ public boolean isDecryptionCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.DECRYPTION); } /** * Indicate whether this credential can be used for verification * @return true if the credential has a {@link Saml2X509CredentialType#VERIFICATION} * type */ public boolean isVerificationCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.VERIFICATION); } /** * Indicate whether this credential can be used for encryption * @return true if the credential has a {@link Saml2X509CredentialType#ENCRYPTION} * type */ public boolean isEncryptionCredential() { return getCredentialTypes().contains(Saml2X509CredentialType.ENCRYPTION); } /** * List all this credential's intended usages * @return the set of this credential's intended usages */ public Set<Saml2X509CredentialType> getCredentialTypes() { return this.credentialTypes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Saml2X509Credential that = (Saml2X509Credential) o; return Objects.equals(this.privateKey, that.privateKey) && this.certificate.equals(that.certificate) && this.credentialTypes.equals(that.credentialTypes); } @Override public int hashCode() { return Objects.hash(this.privateKey, this.certificate, this.credentialTypes); } private void validateUsages(Saml2X509CredentialType[] usages, Saml2X509CredentialType... validUsages) { for (Saml2X509CredentialType usage : usages) { boolean valid = false; for (Saml2X509CredentialType validUsage : validUsages) { if (usage == validUsage) { valid = true; break; } } Assert.state(valid, () -> usage + " is not a valid usage for this credential"); } } public enum Saml2X509CredentialType { VERIFICATION, ENCRYPTION, SIGNING, DECRYPTION, } }
8,160
33.146444
117
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/DefaultSaml2AuthenticatedPrincipalMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; /** * Jackson Mixin class helps in serialize/deserialize * {@link DefaultSaml2AuthenticatedPrincipal}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Ulrich Grave * @since 5.7 * @see DefaultSaml2AuthenticatedPrincipalDeserializer * @see Saml2Jackson2Module * @see SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) class DefaultSaml2AuthenticatedPrincipalMixin { @JsonProperty("registrationId") String registrationId; DefaultSaml2AuthenticatedPrincipalMixin(@JsonProperty("name") String name, @JsonProperty("attributes") Map<String, List<Object>> attributes, @JsonProperty("sessionIndexes") List<String> sessionIndexes) { } }
2,052
33.216667
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2ErrorMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.saml2.core.Saml2Error; /** * This mixin class is used to serialize/deserialize {@link Saml2Error}. * * @author Ulrich Grave * @since 5.7 * @see Saml2Error * @see Saml2Jackson2Module */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) class Saml2ErrorMixin { @JsonCreator Saml2ErrorMixin(@JsonProperty("errorCode") String errorCode, @JsonProperty("description") String description) { } }
1,602
33.847826
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2AuthenticationMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import java.util.Collection; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.core.AuthenticatedPrincipal; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; /** * Jackson Mixin class helps in serialize/deserialize {@link Saml2Authentication}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Ulrich Grave * @since 5.7 * @see Saml2AuthenticationDeserializer * @see Saml2Jackson2Module * @see SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(value = { "authenticated" }, ignoreUnknown = true) class Saml2AuthenticationMixin { @JsonCreator Saml2AuthenticationMixin(@JsonProperty("principal") AuthenticatedPrincipal principal, @JsonProperty("saml2Response") String saml2Response, @JsonProperty("authorities") Collection<? extends GrantedAuthority> authorities) { } }
2,207
36.423729
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2Jackson2Module.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.module.SimpleModule; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.provider.service.authentication.DefaultSaml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2Authentication; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; /** * Jackson module for saml2-service-provider. This module register * {@link Saml2AuthenticationMixin}, {@link DefaultSaml2AuthenticatedPrincipalMixin}, * {@link Saml2LogoutRequestMixin}, {@link Saml2RedirectAuthenticationRequestMixin}, * {@link Saml2PostAuthenticationRequestMixin}, {@link Saml2ErrorMixin} and * {@link Saml2AuthenticationExceptionMixin}. * * @author Ulrich Grave * @since 5.7 * @see SecurityJackson2Modules */ public class Saml2Jackson2Module extends SimpleModule { public Saml2Jackson2Module() { super(Saml2Jackson2Module.class.getName(), new Version(1, 0, 0, null, null, null)); } @Override public void setupModule(SetupContext context) { context.setMixInAnnotations(Saml2Authentication.class, Saml2AuthenticationMixin.class); context.setMixInAnnotations(DefaultSaml2AuthenticatedPrincipal.class, DefaultSaml2AuthenticatedPrincipalMixin.class); context.setMixInAnnotations(Saml2LogoutRequest.class, Saml2LogoutRequestMixin.class); context.setMixInAnnotations(Saml2RedirectAuthenticationRequest.class, Saml2RedirectAuthenticationRequestMixin.class); context.setMixInAnnotations(Saml2PostAuthenticationRequest.class, Saml2PostAuthenticationRequestMixin.class); context.setMixInAnnotations(Saml2Error.class, Saml2ErrorMixin.class); context.setMixInAnnotations(Saml2AuthenticationException.class, Saml2AuthenticationExceptionMixin.class); } }
2,940
46.435484
111
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2PostAuthenticationRequestMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; /** * Jackson Mixin class helps in serialize/deserialize * {@link Saml2PostAuthenticationRequest}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Ulrich Grave * @since 5.7 * @see Saml2Jackson2Module * @see SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) class Saml2PostAuthenticationRequestMixin { @JsonCreator Saml2PostAuthenticationRequestMixin(@JsonProperty("samlRequest") String samlRequest, @JsonProperty("relayState") String relayState, @JsonProperty("authenticationRequestUri") String authenticationRequestUri, @JsonProperty("relyingPartyRegistrationId") String relyingPartyRegistrationId, @JsonProperty("id") String id) { } }
2,068
35.946429
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2LogoutRequestMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import java.util.Map; import java.util.function.Function; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; /** * Jackson Mixin class helps in serialize/deserialize {@link Saml2LogoutRequest}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Ulrich Grave * @since 5.7 * @see Saml2Jackson2Module * @see SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) class Saml2LogoutRequestMixin { @JsonIgnore Function<Map<String, String>, String> encoder; @JsonCreator Saml2LogoutRequestMixin(@JsonProperty("location") String location, @JsonProperty("relayState") Saml2MessageBinding relayState, @JsonProperty("parameters") Map<String, String> parameters, @JsonProperty("id") String id, @JsonProperty("relyingPartyRegistrationId") String relyingPartyRegistrationId) { } }
2,279
35.774194
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2RedirectAuthenticationRequestMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; /** * Jackson Mixin class helps in serialize/deserialize * {@link Saml2RedirectAuthenticationRequest}. * * <pre> * ObjectMapper mapper = new ObjectMapper(); * mapper.registerModule(new Saml2Jackson2Module()); * </pre> * * @author Ulrich Grave * @since 5.7 * @see Saml2Jackson2Module * @see SecurityJackson2Modules */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true) class Saml2RedirectAuthenticationRequestMixin { @JsonCreator Saml2RedirectAuthenticationRequestMixin(@JsonProperty("samlRequest") String samlRequest, @JsonProperty("sigAlg") String sigAlg, @JsonProperty("signature") String signature, @JsonProperty("relayState") String relayState, @JsonProperty("authenticationRequestUri") String authenticationRequestUri, @JsonProperty("relyingPartyRegistrationId") String relyingPartyRegistrationId, @JsonProperty("id") String id) { } }
2,171
37.105263
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/jackson2/Saml2AuthenticationExceptionMixin.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.jackson2; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; /** * This mixin class is used to serialize/deserialize {@link Saml2AuthenticationException}. * * @author Ulrich Grave * @since 5.7 * @see Saml2AuthenticationException * @see Saml2Jackson2Module */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE) @JsonIgnoreProperties(ignoreUnknown = true, value = { "cause", "stackTrace", "suppressedExceptions" }) class Saml2AuthenticationExceptionMixin { @JsonCreator Saml2AuthenticationExceptionMixin(@JsonProperty("error") Saml2Error error, @JsonProperty("detailMessage") String message) { } }
1,834
37.229167
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrations.java
/* * 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.registration; import java.io.IOException; import java.io.InputStream; import java.util.Collection; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.ResourceLoader; import org.springframework.security.saml2.Saml2Exception; /** * A utility class for constructing instances of {@link RelyingPartyRegistration} * * @author Josh Cummings * @author Ryan Cassar * @author Marcus da Coregio * @since 5.4 */ public final class RelyingPartyRegistrations { private static final OpenSamlMetadataRelyingPartyRegistrationConverter relyingPartyRegistrationConverter = new OpenSamlMetadataRelyingPartyRegistrationConverter(); private static final ResourceLoader resourceLoader = new DefaultResourceLoader(); private RelyingPartyRegistrations() { } /** * Return a {@link RelyingPartyRegistration.Builder} based off of the given SAML 2.0 * Asserting Party (IDP) metadata location. * * Valid locations can be classpath- or file-based or they can be HTTP endpoints. Some * valid endpoints might include: * * <pre> * metadataLocation = "classpath:asserting-party-metadata.xml"; * metadataLocation = "file:asserting-party-metadata.xml"; * metadataLocation = "https://ap.example.org/metadata"; * </pre> * * Note that by default the registrationId is set to be the given metadata location, * but this will most often not be sufficient. To complete the configuration, most * applications will also need to provide a registrationId, like so: * * <pre> * RelyingPartyRegistration registration = RelyingPartyRegistrations * .fromMetadataLocation(metadataLocation) * .registrationId("registration-id") * .build(); * </pre> * * Also note that an {@code IDPSSODescriptor} typically only contains information * about the asserting party. Thus, you will need to remember to still populate * anything about the relying party, like any private keys the relying party will use * for signing AuthnRequests. * @param metadataLocation The classpath- or file-based locations or HTTP endpoints of * the asserting party metadata file * @return the {@link RelyingPartyRegistration.Builder} for further configuration */ public static RelyingPartyRegistration.Builder fromMetadataLocation(String metadataLocation) { try (InputStream source = resourceLoader.getResource(metadataLocation).getInputStream()) { return fromMetadata(source); } catch (IOException ex) { if (ex.getCause() instanceof Saml2Exception) { throw (Saml2Exception) ex.getCause(); } throw new Saml2Exception(ex); } } /** * Return a {@link RelyingPartyRegistration.Builder} based off of the given SAML 2.0 * Asserting Party (IDP) metadata. * * <p> * This method is intended for scenarios when the metadata is looked up by a separate * mechanism. One such example is when the metadata is stored in a database. * </p> * * <p> * <strong>The callers of this method are accountable for closing the * {@code InputStream} source.</strong> * </p> * * Note that by default the registrationId is set to be the given metadata location, * but this will most often not be sufficient. To complete the configuration, most * applications will also need to provide a registrationId, like so: * * <pre> * String xml = fromDatabase(); * try (InputStream source = new ByteArrayInputStream(xml.getBytes())) { * RelyingPartyRegistration registration = RelyingPartyRegistrations * .fromMetadata(source) * .registrationId("registration-id") * .build(); * } * </pre> * * Also note that an {@code IDPSSODescriptor} typically only contains information * about the asserting party. Thus, you will need to remember to still populate * anything about the relying party, like any private keys the relying party will use * for signing AuthnRequests. * @param source the {@link InputStream} source containing the asserting party * metadata * @return the {@link RelyingPartyRegistration.Builder} for further configuration * @since 5.6 */ public static RelyingPartyRegistration.Builder fromMetadata(InputStream source) { return collectionFromMetadata(source).iterator().next(); } /** * Return a {@link Collection} of {@link RelyingPartyRegistration.Builder}s based off * of the given SAML 2.0 Asserting Party (IDP) metadata location. * * Valid locations can be classpath- or file-based or they can be HTTP endpoints. Some * valid endpoints might include: * * <pre> * metadataLocation = "classpath:asserting-party-metadata.xml"; * metadataLocation = "file:asserting-party-metadata.xml"; * metadataLocation = "https://ap.example.org/metadata"; * </pre> * * Note that by default the registrationId is set to be the given metadata location, * but this will most often not be sufficient. To complete the configuration, most * applications will also need to provide a registrationId, like so: * * <pre> * Iterable&lt;RelyingPartyRegistration&gt; registrations = RelyingPartyRegistrations * .collectionFromMetadataLocation(location).iterator(); * RelyingPartyRegistration one = registrations.next().registrationId("one").build(); * RelyingPartyRegistration two = registrations.next().registrationId("two").build(); * return new InMemoryRelyingPartyRegistrationRepository(one, two); * </pre> * * Also note that an {@code IDPSSODescriptor} typically only contains information * about the asserting party. Thus, you will need to remember to still populate * anything about the relying party, like any private keys the relying party will use * for signing AuthnRequests. * @param location The classpath- or file-based locations or HTTP endpoints of the * asserting party metadata file * @return the {@link Collection} of {@link RelyingPartyRegistration.Builder}s for * further configuration * @since 5.7 */ public static Collection<RelyingPartyRegistration.Builder> collectionFromMetadataLocation(String location) { try (InputStream source = resourceLoader.getResource(location).getInputStream()) { return collectionFromMetadata(source); } catch (IOException ex) { if (ex.getCause() instanceof Saml2Exception) { throw (Saml2Exception) ex.getCause(); } throw new Saml2Exception(ex); } } /** * Return a {@link Collection} of {@link RelyingPartyRegistration.Builder}s based off * of the given SAML 2.0 Asserting Party (IDP) metadata. * * <p> * This method is intended for scenarios when the metadata is looked up by a separate * mechanism. One such example is when the metadata is stored in a database. * </p> * * <p> * <strong>The callers of this method are accountable for closing the * {@code InputStream} source.</strong> * </p> * * Note that by default the registrationId is set to be the given metadata location, * but this will most often not be sufficient. To complete the configuration, most * applications will also need to provide a registrationId, like so: * * <pre> * String xml = fromDatabase(); * try (InputStream source = new ByteArrayInputStream(xml.getBytes())) { * Iterator&lt;RelyingPartyRegistration&gt; registrations = RelyingPartyRegistrations * .collectionFromMetadata(source).iterator(); * RelyingPartyRegistration one = registrations.next().registrationId("one").build(); * RelyingPartyRegistration two = registrations.next().registrationId("two").build(); * return new InMemoryRelyingPartyRegistrationRepository(one, two); * } * </pre> * * Also note that an {@code IDPSSODescriptor} typically only contains information * about the asserting party. Thus, you will need to remember to still populate * anything about the relying party, like any private keys the relying party will use * for signing AuthnRequests. * @param source the {@link InputStream} source containing the asserting party * metadata * @return the {@link Collection} of {@link RelyingPartyRegistration.Builder}s for * further configuration * @since 5.7 */ public static Collection<RelyingPartyRegistration.Builder> collectionFromMetadata(InputStream source) { return relyingPartyRegistrationConverter.convert(source); } }
8,926
39.577273
164
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistrationRepository.java
/* * 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.provider.service.registration; /** * A repository for {@link RelyingPartyRegistration}s * * @author Filip Hanik * @author Josh Cummings * @since 5.2 */ public interface RelyingPartyRegistrationRepository { /** * Returns the relying party registration identified by the provided * {@code registrationId}, or {@code null} if not found. * @param registrationId the registration identifier * @return the {@link RelyingPartyRegistration} if found, otherwise {@code null} */ RelyingPartyRegistration findByRegistrationId(String registrationId); /** * Returns the unique relying party registration associated with the asserting party's * {@code entityId} or {@code null} if there is no unique match. * @param entityId the asserting party's entity id * @return the unique {@link RelyingPartyRegistration} associated the given asserting * party; {@code null} of there is no unique match asserting party * @since 6.1 */ default RelyingPartyRegistration findUniqueByAssertingPartyEntityId(String entityId) { return findByRegistrationId(entityId); } }
1,747
34.673469
87
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter.java
/* * 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.registration; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import org.springframework.security.saml2.core.OpenSamlInitializationService; /** * An {@link HttpMessageConverter} that takes an {@code IDPSSODescriptor} in an HTTP * response and converts it into a {@link RelyingPartyRegistration.Builder}. * * The primary use case for this is constructing a {@link RelyingPartyRegistration} for * inclusion in a {@link RelyingPartyRegistrationRepository}. To do so, you can include an * instance of this converter in a {@link org.springframework.web.client.RestOperations} * like so: * * <pre> * RestOperations rest = new RestTemplate(Collections.singletonList( * new RelyingPartyRegistrationsBuilderHttpMessageConverter())); * RelyingPartyRegistration.Builder builder = rest.getForObject * ("https://idp.example.org/metadata", RelyingPartyRegistration.Builder.class); * RelyingPartyRegistration registration = builder.registrationId("registration-id").build(); * </pre> * * Note that this will only configure the asserting party (IDP) half of the * {@link RelyingPartyRegistration}, meaning where and how to send AuthnRequests, how to * verify Assertions, etc. * * To further configure the {@link RelyingPartyRegistration} with relying party (SP) * information, you may invoke the appropriate methods on the builder. * * @author Josh Cummings * @since 5.4 */ public class OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter implements HttpMessageConverter<RelyingPartyRegistration.Builder> { static { OpenSamlInitializationService.initialize(); } private final OpenSamlMetadataRelyingPartyRegistrationConverter converter; /** * Creates a {@link OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter} */ public OpenSamlRelyingPartyRegistrationBuilderHttpMessageConverter() { this.converter = new OpenSamlMetadataRelyingPartyRegistrationConverter(); } @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { return RelyingPartyRegistration.Builder.class.isAssignableFrom(clazz); } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { return false; } @Override public List<MediaType> getSupportedMediaTypes() { return Arrays.asList(MediaType.APPLICATION_XML, MediaType.TEXT_XML); } @Override public RelyingPartyRegistration.Builder read(Class<? extends RelyingPartyRegistration.Builder> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return this.converter.convert(inputMessage.getBody()).iterator().next(); } @Override public void write(RelyingPartyRegistration.Builder builder, MediaType contentType, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException { throw new HttpMessageNotWritableException("This converter cannot write a RelyingPartyRegistration.Builder"); } }
3,951
37.745098
116
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlAssertingPartyDetails.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.registration; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.springframework.security.saml2.core.Saml2X509Credential; /** * A {@link RelyingPartyRegistration.AssertingPartyDetails} that contains * OpenSAML-specific members * * @author Josh Cummings * @since 5.7 */ public final class OpenSamlAssertingPartyDetails extends RelyingPartyRegistration.AssertingPartyDetails { private final EntityDescriptor descriptor; OpenSamlAssertingPartyDetails(RelyingPartyRegistration.AssertingPartyDetails details, EntityDescriptor descriptor) { super(details.getEntityId(), details.getWantAuthnRequestsSigned(), details.getSigningAlgorithms(), details.getVerificationX509Credentials(), details.getEncryptionX509Credentials(), details.getSingleSignOnServiceLocation(), details.getSingleSignOnServiceBinding(), details.getSingleLogoutServiceLocation(), details.getSingleLogoutServiceResponseLocation(), details.getSingleLogoutServiceBinding()); this.descriptor = descriptor; } /** * Get the {@link EntityDescriptor} that underlies this * {@link org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.AssertingPartyDetails} * @return the {@link EntityDescriptor} */ public EntityDescriptor getEntityDescriptor() { return this.descriptor; } /** * Use this {@link EntityDescriptor} to begin building an * {@link org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.AssertingPartyDetails} * @param entity the {@link EntityDescriptor} to use * @return the * {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails.Builder} * for further configurations */ public static OpenSamlAssertingPartyDetails.Builder withEntityDescriptor(EntityDescriptor entity) { return new OpenSamlAssertingPartyDetails.Builder(entity); } /** * An OpenSAML version of * {@link org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.AssertingPartyDetails.Builder} * that contains the underlying {@link EntityDescriptor} */ public static final class Builder extends RelyingPartyRegistration.AssertingPartyDetails.Builder { private EntityDescriptor descriptor; private Builder(EntityDescriptor descriptor) { this.descriptor = descriptor; } /** * {@inheritDoc} */ @Override public Builder entityId(String entityId) { return (Builder) super.entityId(entityId); } /** * {@inheritDoc} */ @Override public Builder wantAuthnRequestsSigned(boolean wantAuthnRequestsSigned) { return (Builder) super.wantAuthnRequestsSigned(wantAuthnRequestsSigned); } /** * {@inheritDoc} */ @Override public Builder signingAlgorithms(Consumer<List<String>> signingMethodAlgorithmsConsumer) { return (Builder) super.signingAlgorithms(signingMethodAlgorithmsConsumer); } /** * {@inheritDoc} */ @Override public Builder verificationX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.verificationX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder encryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.encryptionX509Credentials(credentialsConsumer); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) { return (Builder) super.singleSignOnServiceLocation(singleSignOnServiceLocation); } /** * {@inheritDoc} */ @Override public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) { return (Builder) super.singleSignOnServiceBinding(singleSignOnServiceBinding); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation); } /** * {@inheritDoc} */ @Override public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { return (Builder) super.singleLogoutServiceBinding(singleLogoutServiceBinding); } /** * Build an * {@link org.springframework.security.saml2.provider.service.registration.OpenSamlAssertingPartyDetails} * @return */ @Override public OpenSamlAssertingPartyDetails build() { return new OpenSamlAssertingPartyDetails(super.build(), this.descriptor); } } }
5,573
31.034483
131
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/InMemoryRelyingPartyRegistrationRepository.java
/* * 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.registration; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.util.Assert; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; /** * An in-memory implementation of {@link RelyingPartyRegistrationRepository}. Also * implements {@link Iterable} to simplify the default login page. * * @author Filip Hanik * @author Josh Cummings * @since 5.2 */ public class InMemoryRelyingPartyRegistrationRepository implements RelyingPartyRegistrationRepository, Iterable<RelyingPartyRegistration> { private final Map<String, RelyingPartyRegistration> byRegistrationId; private final Map<String, List<RelyingPartyRegistration>> byAssertingPartyEntityId; public InMemoryRelyingPartyRegistrationRepository(RelyingPartyRegistration... registrations) { this(Arrays.asList(registrations)); } public InMemoryRelyingPartyRegistrationRepository(Collection<RelyingPartyRegistration> registrations) { Assert.notEmpty(registrations, "registrations cannot be empty"); this.byRegistrationId = createMappingToIdentityProvider(registrations); this.byAssertingPartyEntityId = createMappingByAssertingPartyEntityId(registrations); } private static Map<String, RelyingPartyRegistration> createMappingToIdentityProvider( Collection<RelyingPartyRegistration> rps) { LinkedHashMap<String, RelyingPartyRegistration> result = new LinkedHashMap<>(); for (RelyingPartyRegistration rp : rps) { Assert.notNull(rp, "relying party collection cannot contain null values"); String key = rp.getRegistrationId(); Assert.notNull(key, "relying party identifier cannot be null"); Assert.isNull(result.get(key), () -> "relying party duplicate identifier '" + key + "' detected."); result.put(key, rp); } return Collections.unmodifiableMap(result); } private static Map<String, List<RelyingPartyRegistration>> createMappingByAssertingPartyEntityId( Collection<RelyingPartyRegistration> rps) { MultiValueMap<String, RelyingPartyRegistration> result = new LinkedMultiValueMap<>(); for (RelyingPartyRegistration rp : rps) { result.add(rp.getAssertingPartyDetails().getEntityId(), rp); } return Collections.unmodifiableMap(result); } @Override public RelyingPartyRegistration findByRegistrationId(String id) { return this.byRegistrationId.get(id); } @Override public RelyingPartyRegistration findUniqueByAssertingPartyEntityId(String entityId) { Collection<RelyingPartyRegistration> registrations = this.byAssertingPartyEntityId.get(entityId); if (registrations == null) { return null; } if (registrations.size() > 1) { return null; } return registrations.iterator().next(); } @Override public Iterator<RelyingPartyRegistration> iterator() { return this.byRegistrationId.values().iterator(); } }
3,646
35.108911
104
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/Saml2MessageBinding.java
/* * 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.provider.service.registration; /** * The type of bindings that messages are exchanged using Supported bindings are * {@code urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST} and * {@code urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect}. In addition there is * support for {@code urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect} with an XML * signature in the message rather than query parameters. * @since 5.3 */ public enum Saml2MessageBinding { POST("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"), REDIRECT( "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"); private final String urn; Saml2MessageBinding(String s) { this.urn = s; } /** * Returns the URN value from the SAML 2 specification for this binding. * @return URN value representing this binding */ public String getUrn() { return this.urn; } /** * Attempt to resolve the provided algorithm name to a {@code Saml2MessageBinding}. * @param name the algorithm name * @return the resolved {@code Saml2MessageBinding}, or {@code null} if not found * @since 5.5 */ public static Saml2MessageBinding from(String name) { for (Saml2MessageBinding value : values()) { if (value.getUrn().equals(name)) { return value; } } return null; } }
1,930
30.145161
85
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/RelyingPartyRegistration.java
/* * 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.registration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.function.Consumer; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * Represents a configured relying party (aka Service Provider) and asserting party (aka * Identity Provider) pair. * * <p> * Each RP/AP pair is uniquely identified using a {@code registrationId}, an arbitrary * string. * * <p> * A fully configured registration may look like: * * <pre> * String registrationId = "simplesamlphp"; * * String relyingPartyEntityId = "{baseUrl}/saml2/service-provider-metadata/{registrationId}"; * String assertionConsumerServiceLocation = "{baseUrl}/login/saml2/sso/{registrationId}"; * Saml2X509Credential relyingPartySigningCredential = ...; * * String assertingPartyEntityId = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/metadata.php"; * String singleSignOnServiceLocation = "https://simplesaml-for-spring-saml.apps.pcfone.io/saml2/idp/SSOService.php"; * Saml2X509Credential assertingPartyVerificationCredential = ...; * * * RelyingPartyRegistration rp = RelyingPartyRegistration.withRegistrationId(registrationId) * .entityId(relyingPartyEntityId) * .assertionConsumerServiceLocation(assertingConsumerServiceLocation) * .signingX509Credentials((c) -&gt; c.add(relyingPartySigningCredential)) * .assertingPartyDetails((details) -&gt; details * .entityId(assertingPartyEntityId)); * .singleSignOnServiceLocation(singleSignOnServiceLocation)) * .verifyingX509Credentials((c) -&gt; c.add(assertingPartyVerificationCredential)) * .build(); * </pre> * * @author Filip Hanik * @author Josh Cummings * @since 5.2 */ public class RelyingPartyRegistration { private final String registrationId; private final String entityId; private final String assertionConsumerServiceLocation; private final Saml2MessageBinding assertionConsumerServiceBinding; private final String singleLogoutServiceLocation; private final String singleLogoutServiceResponseLocation; private final Collection<Saml2MessageBinding> singleLogoutServiceBindings; private final String nameIdFormat; private final boolean authnRequestsSigned; private final AssertingPartyDetails assertingPartyDetails; private final Collection<Saml2X509Credential> decryptionX509Credentials; private final Collection<Saml2X509Credential> signingX509Credentials; protected RelyingPartyRegistration(String registrationId, String entityId, String assertionConsumerServiceLocation, Saml2MessageBinding assertionConsumerServiceBinding, String singleLogoutServiceLocation, String singleLogoutServiceResponseLocation, Collection<Saml2MessageBinding> singleLogoutServiceBindings, AssertingPartyDetails assertingPartyDetails, String nameIdFormat, boolean authnRequestsSigned, Collection<Saml2X509Credential> decryptionX509Credentials, Collection<Saml2X509Credential> signingX509Credentials) { Assert.hasText(registrationId, "registrationId cannot be empty"); Assert.hasText(entityId, "entityId cannot be empty"); Assert.hasText(assertionConsumerServiceLocation, "assertionConsumerServiceLocation cannot be empty"); Assert.notNull(assertionConsumerServiceBinding, "assertionConsumerServiceBinding cannot be null"); Assert.isTrue(singleLogoutServiceLocation == null || !CollectionUtils.isEmpty(singleLogoutServiceBindings), "singleLogoutServiceBindings cannot be null or empty when singleLogoutServiceLocation is set"); Assert.notNull(assertingPartyDetails, "assertingPartyDetails cannot be null"); Assert.notNull(decryptionX509Credentials, "decryptionX509Credentials cannot be null"); for (Saml2X509Credential c : decryptionX509Credentials) { Assert.notNull(c, "decryptionX509Credentials cannot contain null elements"); Assert.isTrue(c.isDecryptionCredential(), "All decryptionX509Credentials must have a usage of DECRYPTION set"); } Assert.notNull(signingX509Credentials, "signingX509Credentials cannot be null"); for (Saml2X509Credential c : signingX509Credentials) { Assert.notNull(c, "signingX509Credentials cannot contain null elements"); Assert.isTrue(c.isSigningCredential(), "All signingX509Credentials must have a usage of SIGNING set"); } this.registrationId = registrationId; this.entityId = entityId; this.assertionConsumerServiceLocation = assertionConsumerServiceLocation; this.assertionConsumerServiceBinding = assertionConsumerServiceBinding; this.singleLogoutServiceLocation = singleLogoutServiceLocation; this.singleLogoutServiceResponseLocation = singleLogoutServiceResponseLocation; this.singleLogoutServiceBindings = Collections.unmodifiableList(new LinkedList<>(singleLogoutServiceBindings)); this.nameIdFormat = nameIdFormat; this.authnRequestsSigned = authnRequestsSigned; this.assertingPartyDetails = assertingPartyDetails; this.decryptionX509Credentials = Collections.unmodifiableList(new LinkedList<>(decryptionX509Credentials)); this.signingX509Credentials = Collections.unmodifiableList(new LinkedList<>(signingX509Credentials)); } /** * Copy the properties in this {@link RelyingPartyRegistration} into a {@link Builder} * @return a {@link Builder} based off of the properties in this * {@link RelyingPartyRegistration} * @since 6.1 */ public Builder mutate() { AssertingPartyDetails party = this.assertingPartyDetails; return withRegistrationId(this.registrationId).entityId(this.entityId) .signingX509Credentials((c) -> c.addAll(this.signingX509Credentials)) .decryptionX509Credentials((c) -> c.addAll(this.decryptionX509Credentials)) .assertionConsumerServiceLocation(this.assertionConsumerServiceLocation) .assertionConsumerServiceBinding(this.assertionConsumerServiceBinding) .singleLogoutServiceLocation(this.singleLogoutServiceLocation) .singleLogoutServiceResponseLocation(this.singleLogoutServiceResponseLocation) .singleLogoutServiceBindings((c) -> c.addAll(this.singleLogoutServiceBindings)) .nameIdFormat(this.nameIdFormat).authnRequestsSigned(this.authnRequestsSigned) .assertingPartyDetails((assertingParty) -> assertingParty.entityId(party.getEntityId()) .wantAuthnRequestsSigned(party.getWantAuthnRequestsSigned()) .signingAlgorithms((algorithms) -> algorithms.addAll(party.getSigningAlgorithms())) .verificationX509Credentials((c) -> c.addAll(party.getVerificationX509Credentials())) .encryptionX509Credentials((c) -> c.addAll(party.getEncryptionX509Credentials())) .singleSignOnServiceLocation(party.getSingleSignOnServiceLocation()) .singleSignOnServiceBinding(party.getSingleSignOnServiceBinding()) .singleLogoutServiceLocation(party.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(party.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBinding(party.getSingleLogoutServiceBinding())); } /** * Get the unique registration id for this RP/AP pair * @return the unique registration id for this RP/AP pair */ public String getRegistrationId() { return this.registrationId; } /** * Get the relying party's <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.9%20EntityDescriptor">EntityID</a>. * * <p> * Equivalent to the value found in the relying party's &lt;EntityDescriptor * EntityID="..."/&gt; * * <p> * This value may contain a number of placeholders, which need to be resolved before * use. They are {@code baseUrl}, {@code registrationId}, {@code baseScheme}, * {@code baseHost}, and {@code basePort}. * @return the relying party's EntityID * @since 5.4 */ public String getEntityId() { return this.entityId; } /** * Get the AssertionConsumerService Location. Equivalent to the value found in * &lt;AssertionConsumerService Location="..."/&gt; in the relying party's * &lt;SPSSODescriptor&gt;. * * This value may contain a number of placeholders, which need to be resolved before * use. They are {@code baseUrl}, {@code registrationId}, {@code baseScheme}, * {@code baseHost}, and {@code basePort}. * @return the AssertionConsumerService Location * @since 5.4 */ public String getAssertionConsumerServiceLocation() { return this.assertionConsumerServiceLocation; } /** * Get the AssertionConsumerService Binding. Equivalent to the value found in * &lt;AssertionConsumerService Binding="..."/&gt; in the relying party's * &lt;SPSSODescriptor&gt;. * @return the AssertionConsumerService Binding * @since 5.4 */ public Saml2MessageBinding getAssertionConsumerServiceBinding() { return this.assertionConsumerServiceBinding; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Binding</a> * * * <p> * Equivalent to the value found in &lt;SingleLogoutService Binding="..."/&gt; in the * relying party's &lt;SPSSODescriptor&gt;. * @return the SingleLogoutService Binding * @since 5.6 */ public Saml2MessageBinding getSingleLogoutServiceBinding() { Assert.state(this.singleLogoutServiceBindings.size() == 1, "Method does not support multiple bindings."); return this.singleLogoutServiceBindings.iterator().next(); } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Binding</a> * <p> * Equivalent to the value found in &lt;SingleLogoutService Binding="..."/&gt; in the * relying party's &lt;SPSSODescriptor&gt;. * @return the SingleLogoutService Binding * @since 5.8 */ public Collection<Saml2MessageBinding> getSingleLogoutServiceBindings() { return this.singleLogoutServiceBindings; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Location="..."/&gt; in the * relying party's &lt;SPSSODescriptor&gt;. * @return the SingleLogoutService Location * @since 5.6 */ public String getSingleLogoutServiceLocation() { return this.singleLogoutServiceLocation; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Response Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService * ResponseLocation="..."/&gt; in the relying party's &lt;SPSSODescriptor&gt;. * @return the SingleLogoutService Response Location * @since 5.6 */ public String getSingleLogoutServiceResponseLocation() { return this.singleLogoutServiceResponseLocation; } /** * Get the NameID format. * @return the NameID format * @since 5.7 */ public String getNameIdFormat() { return this.nameIdFormat; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=18"> * AuthnRequestsSigned</a> setting. If {@code true}, the relying party will sign all * AuthnRequests, regardless of asserting party preference. * * <p> * Note that Spring Security will sign the request if either * {@link #isAuthnRequestsSigned()} is {@code true} or * {@link AssertingPartyDetails#getWantAuthnRequestsSigned()} is {@code true}. * @return the relying-party preference * @since 6.1 */ public boolean isAuthnRequestsSigned() { return this.authnRequestsSigned; } /** * Get the {@link Collection} of decryption {@link Saml2X509Credential}s associated * with this relying party * @return the {@link Collection} of decryption {@link Saml2X509Credential}s * associated with this relying party * @since 5.4 */ public Collection<Saml2X509Credential> getDecryptionX509Credentials() { return this.decryptionX509Credentials; } /** * Get the {@link Collection} of signing {@link Saml2X509Credential}s associated with * this relying party * @return the {@link Collection} of signing {@link Saml2X509Credential}s associated * with this relying party * @since 5.4 */ public Collection<Saml2X509Credential> getSigningX509Credentials() { return this.signingX509Credentials; } /** * Get the configuration details for the Asserting Party * @return the {@link AssertingPartyDetails} * @since 5.4 */ public AssertingPartyDetails getAssertingPartyDetails() { return this.assertingPartyDetails; } /** * Creates a {@code RelyingPartyRegistration} {@link Builder} with a known * {@code registrationId} * @param registrationId a string identifier for the {@code RelyingPartyRegistration} * @return {@code Builder} to create a {@code RelyingPartyRegistration} object */ public static Builder withRegistrationId(String registrationId) { Assert.hasText(registrationId, "registrationId cannot be empty"); return new Builder(registrationId, new AssertingPartyDetails.Builder()); } public static Builder withAssertingPartyDetails(AssertingPartyDetails assertingPartyDetails) { Assert.notNull(assertingPartyDetails, "assertingPartyDetails cannot be null"); return withRegistrationId(assertingPartyDetails.getEntityId()).assertingPartyDetails((party) -> party .entityId(assertingPartyDetails.getEntityId()) .wantAuthnRequestsSigned(assertingPartyDetails.getWantAuthnRequestsSigned()) .signingAlgorithms((algorithms) -> algorithms.addAll(assertingPartyDetails.getSigningAlgorithms())) .verificationX509Credentials((c) -> c.addAll(assertingPartyDetails.getVerificationX509Credentials())) .encryptionX509Credentials((c) -> c.addAll(assertingPartyDetails.getEncryptionX509Credentials())) .singleSignOnServiceLocation(assertingPartyDetails.getSingleSignOnServiceLocation()) .singleSignOnServiceBinding(assertingPartyDetails.getSingleSignOnServiceBinding()) .singleLogoutServiceLocation(assertingPartyDetails.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(assertingPartyDetails.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBinding(assertingPartyDetails.getSingleLogoutServiceBinding())); } /** * Creates a {@code RelyingPartyRegistration} {@link Builder} based on an existing * object * @param registration the {@code RelyingPartyRegistration} * @return {@code Builder} to create a {@code RelyingPartyRegistration} object * @deprecated Use {@link #mutate()} instead */ @Deprecated(forRemoval = true, since = "6.1") public static Builder withRelyingPartyRegistration(RelyingPartyRegistration registration) { Assert.notNull(registration, "registration cannot be null"); return withRegistrationId(registration.getRegistrationId()).entityId(registration.getEntityId()) .signingX509Credentials((c) -> c.addAll(registration.getSigningX509Credentials())) .decryptionX509Credentials((c) -> c.addAll(registration.getDecryptionX509Credentials())) .assertionConsumerServiceLocation(registration.getAssertionConsumerServiceLocation()) .assertionConsumerServiceBinding(registration.getAssertionConsumerServiceBinding()) .singleLogoutServiceLocation(registration.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(registration.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBindings((c) -> c.addAll(registration.getSingleLogoutServiceBindings())) .nameIdFormat(registration.getNameIdFormat()).authnRequestsSigned(registration.isAuthnRequestsSigned()) .assertingPartyDetails((assertingParty) -> assertingParty .entityId(registration.getAssertingPartyDetails().getEntityId()) .wantAuthnRequestsSigned(registration.getAssertingPartyDetails().getWantAuthnRequestsSigned()) .signingAlgorithms((algorithms) -> algorithms .addAll(registration.getAssertingPartyDetails().getSigningAlgorithms())) .verificationX509Credentials((c) -> c .addAll(registration.getAssertingPartyDetails().getVerificationX509Credentials())) .encryptionX509Credentials( (c) -> c.addAll(registration.getAssertingPartyDetails().getEncryptionX509Credentials())) .singleSignOnServiceLocation( registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()) .singleSignOnServiceBinding( registration.getAssertingPartyDetails().getSingleSignOnServiceBinding()) .singleLogoutServiceLocation( registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation( registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBinding( registration.getAssertingPartyDetails().getSingleLogoutServiceBinding())); } /** * The configuration metadata of the Asserting party * * @since 5.4 */ public static class AssertingPartyDetails { private final String entityId; private final boolean wantAuthnRequestsSigned; private List<String> signingAlgorithms; private final Collection<Saml2X509Credential> verificationX509Credentials; private final Collection<Saml2X509Credential> encryptionX509Credentials; private final String singleSignOnServiceLocation; private final Saml2MessageBinding singleSignOnServiceBinding; private final String singleLogoutServiceLocation; private final String singleLogoutServiceResponseLocation; private final Saml2MessageBinding singleLogoutServiceBinding; AssertingPartyDetails(String entityId, boolean wantAuthnRequestsSigned, List<String> signingAlgorithms, Collection<Saml2X509Credential> verificationX509Credentials, Collection<Saml2X509Credential> encryptionX509Credentials, String singleSignOnServiceLocation, Saml2MessageBinding singleSignOnServiceBinding, String singleLogoutServiceLocation, String singleLogoutServiceResponseLocation, Saml2MessageBinding singleLogoutServiceBinding) { Assert.hasText(entityId, "entityId cannot be null or empty"); Assert.notEmpty(signingAlgorithms, "signingAlgorithms cannot be empty"); Assert.notNull(verificationX509Credentials, "verificationX509Credentials cannot be null"); for (Saml2X509Credential credential : verificationX509Credentials) { Assert.notNull(credential, "verificationX509Credentials cannot have null values"); Assert.isTrue(credential.isVerificationCredential(), "All verificationX509Credentials must have a usage of VERIFICATION set"); } Assert.notNull(encryptionX509Credentials, "encryptionX509Credentials cannot be null"); for (Saml2X509Credential credential : encryptionX509Credentials) { Assert.notNull(credential, "encryptionX509Credentials cannot have null values"); Assert.isTrue(credential.isEncryptionCredential(), "All encryptionX509Credentials must have a usage of ENCRYPTION set"); } Assert.notNull(singleSignOnServiceLocation, "singleSignOnServiceLocation cannot be null"); Assert.notNull(singleSignOnServiceBinding, "singleSignOnServiceBinding cannot be null"); this.entityId = entityId; this.wantAuthnRequestsSigned = wantAuthnRequestsSigned; this.signingAlgorithms = signingAlgorithms; this.verificationX509Credentials = verificationX509Credentials; this.encryptionX509Credentials = encryptionX509Credentials; this.singleSignOnServiceLocation = singleSignOnServiceLocation; this.singleSignOnServiceBinding = singleSignOnServiceBinding; this.singleLogoutServiceLocation = singleLogoutServiceLocation; this.singleLogoutServiceResponseLocation = singleLogoutServiceResponseLocation; this.singleLogoutServiceBinding = singleLogoutServiceBinding; } /** * Get the asserting party's <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.9%20EntityDescriptor">EntityID</a>. * * <p> * Equivalent to the value found in the asserting party's &lt;EntityDescriptor * EntityID="..."/&gt; * * <p> * This value may contain a number of placeholders, which need to be resolved * before use. They are {@code baseUrl}, {@code registrationId}, * {@code baseScheme}, {@code baseHost}, and {@code basePort}. * @return the asserting party's EntityID */ public String getEntityId() { return this.entityId; } /** * Get the WantAuthnRequestsSigned setting, indicating the asserting party's * preference that relying parties should sign the AuthnRequest before sending. * @return the WantAuthnRequestsSigned value */ public boolean getWantAuthnRequestsSigned() { return this.wantAuthnRequestsSigned; } /** * Get the list of org.opensaml.saml.ext.saml2alg.SigningMethod Algorithms for * this asserting party, in preference order. * * <p> * Equivalent to the values found in &lt;SigningMethod Algorithm="..."/&gt; in the * asserting party's &lt;IDPSSODescriptor&gt;. * @return the list of SigningMethod Algorithms * @since 5.5 */ public List<String> getSigningAlgorithms() { return this.signingAlgorithms; } /** * Get all verification {@link Saml2X509Credential}s associated with this * asserting party * @return all verification {@link Saml2X509Credential}s associated with this * asserting party * @since 5.4 */ public Collection<Saml2X509Credential> getVerificationX509Credentials() { return this.verificationX509Credentials; } /** * Get all encryption {@link Saml2X509Credential}s associated with this asserting * party * @return all encryption {@link Saml2X509Credential}s associated with this * asserting party * @since 5.4 */ public Collection<Saml2X509Credential> getEncryptionX509Credentials() { return this.encryptionX509Credentials; } /** * Get the <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.5%20Endpoint">SingleSignOnService</a> * Location. * * <p> * Equivalent to the value found in &lt;SingleSignOnService Location="..."/&gt; in * the asserting party's &lt;IDPSSODescriptor&gt;. * @return the SingleSignOnService Location */ public String getSingleSignOnServiceLocation() { return this.singleSignOnServiceLocation; } /** * Get the <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.5%20Endpoint">SingleSignOnService</a> * Binding. * * <p> * Equivalent to the value found in &lt;SingleSignOnService Binding="..."/&gt; in * the asserting party's &lt;IDPSSODescriptor&gt;. * @return the SingleSignOnService Location */ public Saml2MessageBinding getSingleSignOnServiceBinding() { return this.singleSignOnServiceBinding; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Location="..."/&gt; in * the asserting party's &lt;IDPSSODescriptor&gt;. * @return the SingleLogoutService Location * @since 5.6 */ public String getSingleLogoutServiceLocation() { return this.singleLogoutServiceLocation; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Response Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Location="..."/&gt; in * the asserting party's &lt;IDPSSODescriptor&gt;. * @return the SingleLogoutService Response Location * @since 5.6 */ public String getSingleLogoutServiceResponseLocation() { return this.singleLogoutServiceResponseLocation; } /** * Get the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Binding</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Binding="..."/&gt; in * the asserting party's &lt;IDPSSODescriptor&gt;. * @return the SingleLogoutService Binding * @since 5.6 */ public Saml2MessageBinding getSingleLogoutServiceBinding() { return this.singleLogoutServiceBinding; } public static class Builder { private String entityId; private boolean wantAuthnRequestsSigned = true; private List<String> signingAlgorithms = new ArrayList<>(); private Collection<Saml2X509Credential> verificationX509Credentials = new LinkedHashSet<>(); private Collection<Saml2X509Credential> encryptionX509Credentials = new LinkedHashSet<>(); private String singleSignOnServiceLocation; private Saml2MessageBinding singleSignOnServiceBinding = Saml2MessageBinding.REDIRECT; private String singleLogoutServiceLocation; private String singleLogoutServiceResponseLocation; private Saml2MessageBinding singleLogoutServiceBinding = Saml2MessageBinding.REDIRECT; /** * Set the asserting party's <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.9%20EntityDescriptor">EntityID</a>. * Equivalent to the value found in the asserting party's &lt;EntityDescriptor * EntityID="..."/&gt; * @param entityId the asserting party's EntityID * @return the {@link AssertingPartyDetails.Builder} for further configuration */ public Builder entityId(String entityId) { this.entityId = entityId; return this; } /** * Set the WantAuthnRequestsSigned setting, indicating the asserting party's * preference that relying parties should sign the AuthnRequest before * sending. * @param wantAuthnRequestsSigned the WantAuthnRequestsSigned setting * @return the {@link AssertingPartyDetails.Builder} for further configuration */ public Builder wantAuthnRequestsSigned(boolean wantAuthnRequestsSigned) { this.wantAuthnRequestsSigned = wantAuthnRequestsSigned; return this; } /** * Apply this {@link Consumer} to the list of SigningMethod Algorithms * @param signingMethodAlgorithmsConsumer a {@link Consumer} of the list of * SigningMethod Algorithms * @return this {@link AssertingPartyDetails.Builder} for further * configuration * @since 5.5 */ public Builder signingAlgorithms(Consumer<List<String>> signingMethodAlgorithmsConsumer) { signingMethodAlgorithmsConsumer.accept(this.signingAlgorithms); return this; } /** * Apply this {@link Consumer} to the list of {@link Saml2X509Credential}s * @param credentialsConsumer a {@link Consumer} of the {@link List} of * {@link Saml2X509Credential}s * @return the {@link RelyingPartyRegistration.Builder} for further * configuration * @since 5.4 */ public Builder verificationX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { credentialsConsumer.accept(this.verificationX509Credentials); return this; } /** * Apply this {@link Consumer} to the list of {@link Saml2X509Credential}s * @param credentialsConsumer a {@link Consumer} of the {@link List} of * {@link Saml2X509Credential}s * @return the {@link RelyingPartyRegistration.Builder} for further * configuration * @since 5.4 */ public Builder encryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { credentialsConsumer.accept(this.encryptionX509Credentials); return this; } /** * Set the <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.5%20Endpoint">SingleSignOnService</a> * Location. * * <p> * Equivalent to the value found in &lt;SingleSignOnService * Location="..."/&gt; in the asserting party's &lt;IDPSSODescriptor&gt;. * @param singleSignOnServiceLocation the SingleSignOnService Location * @return the {@link AssertingPartyDetails.Builder} for further configuration */ public Builder singleSignOnServiceLocation(String singleSignOnServiceLocation) { this.singleSignOnServiceLocation = singleSignOnServiceLocation; return this; } /** * Set the <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.5%20Endpoint">SingleSignOnService</a> * Binding. * * <p> * Equivalent to the value found in &lt;SingleSignOnService Binding="..."/&gt; * in the asserting party's &lt;IDPSSODescriptor&gt;. * @param singleSignOnServiceBinding the SingleSignOnService Binding * @return the {@link AssertingPartyDetails.Builder} for further configuration */ public Builder singleSignOnServiceBinding(Saml2MessageBinding singleSignOnServiceBinding) { this.singleSignOnServiceBinding = singleSignOnServiceBinding; return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService * Location="..."/&gt; in the asserting party's &lt;IDPSSODescriptor&gt;. * @param singleLogoutServiceLocation the SingleLogoutService Location * @return the {@link AssertingPartyDetails.Builder} for further configuration * @since 5.6 */ public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { this.singleLogoutServiceLocation = singleLogoutServiceLocation; return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Response Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService * ResponseLocation="..."/&gt; in the asserting party's * &lt;IDPSSODescriptor&gt;. * @param singleLogoutServiceResponseLocation the SingleLogoutService Response * Location * @return the {@link AssertingPartyDetails.Builder} for further configuration * @since 5.6 */ public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { this.singleLogoutServiceResponseLocation = singleLogoutServiceResponseLocation; return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Binding</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Binding="..."/&gt; * in the asserting party's &lt;IDPSSODescriptor&gt;. * @param singleLogoutServiceBinding the SingleLogoutService Binding * @return the {@link AssertingPartyDetails.Builder} for further configuration * @since 5.6 */ public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { this.singleLogoutServiceBinding = singleLogoutServiceBinding; return this; } /** * Creates an immutable ProviderDetails object representing the configuration * for an Identity Provider, IDP * @return immutable ProviderDetails object */ public AssertingPartyDetails build() { List<String> signingAlgorithms = this.signingAlgorithms.isEmpty() ? Collections.singletonList(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256) : Collections.unmodifiableList(this.signingAlgorithms); return new AssertingPartyDetails(this.entityId, this.wantAuthnRequestsSigned, signingAlgorithms, this.verificationX509Credentials, this.encryptionX509Credentials, this.singleSignOnServiceLocation, this.singleSignOnServiceBinding, this.singleLogoutServiceLocation, this.singleLogoutServiceResponseLocation, this.singleLogoutServiceBinding); } } } public static class Builder { private String registrationId; private String entityId = "{baseUrl}/saml2/service-provider-metadata/{registrationId}"; private Collection<Saml2X509Credential> signingX509Credentials = new LinkedHashSet<>(); private Collection<Saml2X509Credential> decryptionX509Credentials = new LinkedHashSet<>(); private String assertionConsumerServiceLocation = "{baseUrl}/login/saml2/sso/{registrationId}"; private Saml2MessageBinding assertionConsumerServiceBinding = Saml2MessageBinding.POST; private String singleLogoutServiceLocation; private String singleLogoutServiceResponseLocation; private Collection<Saml2MessageBinding> singleLogoutServiceBindings = new LinkedHashSet<>(); private String nameIdFormat = null; private boolean authnRequestsSigned = false; private AssertingPartyDetails.Builder assertingPartyDetailsBuilder; protected Builder(String registrationId, AssertingPartyDetails.Builder assertingPartyDetailsBuilder) { this.registrationId = registrationId; this.assertingPartyDetailsBuilder = assertingPartyDetailsBuilder; } /** * Sets the {@code registrationId} template. Often be used in URL paths * @param id registrationId for this object, should be unique * @return this object */ public Builder registrationId(String id) { this.registrationId = id; return this; } /** * Set the relying party's <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.9%20EntityDescriptor">EntityID</a>. * Equivalent to the value found in the relying party's &lt;EntityDescriptor * EntityID="..."/&gt; * * This value may contain a number of placeholders. They are {@code baseUrl}, * {@code registrationId}, {@code baseScheme}, {@code baseHost}, and * {@code basePort}. * @param entityId the relying party's EntityID * @return the {@link Builder} for further configuration * @since 5.4 */ public Builder entityId(String entityId) { this.entityId = entityId; return this; } /** * Apply this {@link Consumer} to the {@link Collection} of * {@link Saml2X509Credential}s for the purposes of modifying the * {@link Collection} * @param credentialsConsumer - the {@link Consumer} for modifying the * {@link Collection} * @return the {@link Builder} for further configuration * @since 5.4 */ public Builder signingX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { credentialsConsumer.accept(this.signingX509Credentials); return this; } /** * Apply this {@link Consumer} to the {@link Collection} of * {@link Saml2X509Credential}s for the purposes of modifying the * {@link Collection} * @param credentialsConsumer - the {@link Consumer} for modifying the * {@link Collection} * @return the {@link Builder} for further configuration * @since 5.4 */ public Builder decryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { credentialsConsumer.accept(this.decryptionX509Credentials); return this; } /** * Set the <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.3%20AttributeConsumingService"> * AssertionConsumerService</a> Location. * * <p> * Equivalent to the value found in &lt;AssertionConsumerService * Location="..."/&gt; in the relying party's &lt;SPSSODescriptor&gt; * * <p> * This value may contain a number of placeholders. They are {@code baseUrl}, * {@code registrationId}, {@code baseScheme}, {@code baseHost}, and * {@code basePort}. * @param assertionConsumerServiceLocation the AssertionConsumerService location * @return the {@link Builder} for further configuration * @since 5.4 */ public Builder assertionConsumerServiceLocation(String assertionConsumerServiceLocation) { this.assertionConsumerServiceLocation = assertionConsumerServiceLocation; return this; } /** * Set the <a href= * "https://www.oasis-open.org/committees/download.php/51890/SAML%20MD%20simplified%20overview.pdf#2.3%20AttributeConsumingService"> * AssertionConsumerService</a> Binding. * * <p> * Equivalent to the value found in &lt;AssertionConsumerService * Binding="..."/&gt; in the relying party's &lt;SPSSODescriptor&gt; * @param assertionConsumerServiceBinding the AssertionConsumerService binding * @return the {@link Builder} for further configuration * @since 5.4 */ public Builder assertionConsumerServiceBinding(Saml2MessageBinding assertionConsumerServiceBinding) { this.assertionConsumerServiceBinding = assertionConsumerServiceBinding; return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Binding</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Binding="..."/&gt; in * the relying party's &lt;SPSSODescriptor&gt;. * @param singleLogoutServiceBinding the SingleLogoutService Binding * @return the {@link Builder} for further configuration * @since 5.6 */ public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { return this.singleLogoutServiceBindings((saml2MessageBindings) -> { saml2MessageBindings.clear(); saml2MessageBindings.add(singleLogoutServiceBinding); }); } /** * Apply this {@link Consumer} to the {@link Collection} of * {@link Saml2MessageBinding}s for the purposes of modifying the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Binding</a> {@link Collection}. * * <p> * Equivalent to the value found in &lt;SingleLogoutService Binding="..."/&gt; in * the relying party's &lt;SPSSODescriptor&gt;. * @param bindingsConsumer - the {@link Consumer} for modifying the * {@link Collection} * @return the {@link Builder} for further configuration * @since 5.8 */ public Builder singleLogoutServiceBindings(Consumer<Collection<Saml2MessageBinding>> bindingsConsumer) { bindingsConsumer.accept(this.singleLogoutServiceBindings); return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService Location="..."/&gt; in * the relying party's &lt;SPSSODescriptor&gt;. * @param singleLogoutServiceLocation the SingleLogoutService Location * @return the {@link Builder} for further configuration * @since 5.6 */ public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { this.singleLogoutServiceLocation = singleLogoutServiceLocation; return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=7">SingleLogoutService * Response Location</a> * * <p> * Equivalent to the value found in &lt;SingleLogoutService * ResponseLocation="..."/&gt; in the relying party's &lt;SPSSODescriptor&gt;. * @param singleLogoutServiceResponseLocation the SingleLogoutService Response * Location * @return the {@link Builder} for further configuration * @since 5.6 */ public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { this.singleLogoutServiceResponseLocation = singleLogoutServiceResponseLocation; return this; } /** * Set the NameID format * @param nameIdFormat * @return the {@link Builder} for further configuration * @since 5.7 */ public Builder nameIdFormat(String nameIdFormat) { this.nameIdFormat = nameIdFormat; return this; } /** * Set the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-metadata-2.0-os.pdf#page=18"> * AuthnRequestsSigned</a> setting. If {@code true}, the relying party will sign * all AuthnRequests, 301 asserting party preference. * * <p> * Note that Spring Security will sign the request if either * {@link #isAuthnRequestsSigned()} is {@code true} or * {@link AssertingPartyDetails#getWantAuthnRequestsSigned()} is {@code true}. * @return the {@link Builder} for further configuration * @since 6.1 */ public Builder authnRequestsSigned(Boolean authnRequestsSigned) { this.authnRequestsSigned = authnRequestsSigned; return this; } /** * Apply this {@link Consumer} to further configure the Asserting Party details * @param assertingPartyDetails The {@link Consumer} to apply * @return the {@link Builder} for further configuration * @since 5.4 */ public Builder assertingPartyDetails(Consumer<AssertingPartyDetails.Builder> assertingPartyDetails) { assertingPartyDetails.accept(this.assertingPartyDetailsBuilder); return this; } /** * Constructs a RelyingPartyRegistration object based on the builder * configurations * @return a RelyingPartyRegistration instance */ public RelyingPartyRegistration build() { if (this.singleLogoutServiceResponseLocation == null) { this.singleLogoutServiceResponseLocation = this.singleLogoutServiceLocation; } if (this.singleLogoutServiceBindings.isEmpty()) { this.singleLogoutServiceBindings.add(Saml2MessageBinding.POST); } AssertingPartyDetails party = this.assertingPartyDetailsBuilder.build(); return new RelyingPartyRegistration(this.registrationId, this.entityId, this.assertionConsumerServiceLocation, this.assertionConsumerServiceBinding, this.singleLogoutServiceLocation, this.singleLogoutServiceResponseLocation, this.singleLogoutServiceBindings, party, this.nameIdFormat, this.authnRequestsSigned, this.decryptionX509Credentials, this.signingX509Credentials); } } }
42,502
39.363723
141
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlMetadataRelyingPartyRegistrationConverter.java
/* * 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.registration; import java.io.InputStream; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.io.Unmarshaller; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.ext.saml2alg.SigningMethod; import org.opensaml.saml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.opensaml.saml.saml2.metadata.Extensions; import org.opensaml.saml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml.saml2.metadata.KeyDescriptor; import org.opensaml.saml.saml2.metadata.SingleLogoutService; import org.opensaml.saml.saml2.metadata.SingleSignOnService; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.keyinfo.KeyInfoSupport; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2X509Credential; class OpenSamlMetadataRelyingPartyRegistrationConverter { static { OpenSamlInitializationService.initialize(); } private final XMLObjectProviderRegistry registry; private final ParserPool parserPool; /** * Creates a {@link OpenSamlMetadataRelyingPartyRegistrationConverter} */ OpenSamlMetadataRelyingPartyRegistrationConverter() { this.registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = this.registry.getParserPool(); } OpenSamlRelyingPartyRegistration.Builder convert(EntityDescriptor descriptor) { IDPSSODescriptor idpssoDescriptor = descriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS); if (idpssoDescriptor == null) { throw new Saml2Exception("Metadata response is missing the necessary IDPSSODescriptor element"); } List<Saml2X509Credential> verification = new ArrayList<>(); List<Saml2X509Credential> encryption = new ArrayList<>(); for (KeyDescriptor keyDescriptor : idpssoDescriptor.getKeyDescriptors()) { if (keyDescriptor.getUse().equals(UsageType.SIGNING)) { List<X509Certificate> certificates = certificates(keyDescriptor); for (X509Certificate certificate : certificates) { verification.add(Saml2X509Credential.verification(certificate)); } } if (keyDescriptor.getUse().equals(UsageType.ENCRYPTION)) { List<X509Certificate> certificates = certificates(keyDescriptor); for (X509Certificate certificate : certificates) { encryption.add(Saml2X509Credential.encryption(certificate)); } } if (keyDescriptor.getUse().equals(UsageType.UNSPECIFIED)) { List<X509Certificate> certificates = certificates(keyDescriptor); for (X509Certificate certificate : certificates) { verification.add(Saml2X509Credential.verification(certificate)); encryption.add(Saml2X509Credential.encryption(certificate)); } } } if (verification.isEmpty()) { throw new Saml2Exception( "Metadata response is missing verification certificates, necessary for verifying SAML assertions"); } OpenSamlRelyingPartyRegistration.Builder builder = OpenSamlRelyingPartyRegistration .withAssertingPartyEntityDescriptor(descriptor) .assertingPartyDetails((party) -> party.entityId(descriptor.getEntityID()) .wantAuthnRequestsSigned(Boolean.TRUE.equals(idpssoDescriptor.getWantAuthnRequestsSigned())) .verificationX509Credentials((c) -> c.addAll(verification)) .encryptionX509Credentials((c) -> c.addAll(encryption))); List<SigningMethod> signingMethods = signingMethods(idpssoDescriptor); for (SigningMethod method : signingMethods) { builder.assertingPartyDetails( (party) -> party.signingAlgorithms((algorithms) -> algorithms.add(method.getAlgorithm()))); } if (idpssoDescriptor.getSingleSignOnServices().isEmpty()) { throw new Saml2Exception( "Metadata response is missing a SingleSignOnService, necessary for sending AuthnRequests"); } for (SingleSignOnService singleSignOnService : idpssoDescriptor.getSingleSignOnServices()) { Saml2MessageBinding binding; if (singleSignOnService.getBinding().equals(Saml2MessageBinding.POST.getUrn())) { binding = Saml2MessageBinding.POST; } else if (singleSignOnService.getBinding().equals(Saml2MessageBinding.REDIRECT.getUrn())) { binding = Saml2MessageBinding.REDIRECT; } else { continue; } builder.assertingPartyDetails( (party) -> party.singleSignOnServiceLocation(singleSignOnService.getLocation()) .singleSignOnServiceBinding(binding)); break; } for (SingleLogoutService singleLogoutService : idpssoDescriptor.getSingleLogoutServices()) { Saml2MessageBinding binding; if (singleLogoutService.getBinding().equals(Saml2MessageBinding.POST.getUrn())) { binding = Saml2MessageBinding.POST; } else if (singleLogoutService.getBinding().equals(Saml2MessageBinding.REDIRECT.getUrn())) { binding = Saml2MessageBinding.REDIRECT; } else { continue; } String responseLocation = (singleLogoutService.getResponseLocation() == null) ? singleLogoutService.getLocation() : singleLogoutService.getResponseLocation(); builder.assertingPartyDetails( (party) -> party.singleLogoutServiceLocation(singleLogoutService.getLocation()) .singleLogoutServiceResponseLocation(responseLocation).singleLogoutServiceBinding(binding)); break; } return builder; } Collection<RelyingPartyRegistration.Builder> convert(InputStream inputStream) { List<RelyingPartyRegistration.Builder> builders = new ArrayList<>(); XMLObject xmlObject = xmlObject(inputStream); if (xmlObject instanceof EntitiesDescriptor) { EntitiesDescriptor descriptors = (EntitiesDescriptor) xmlObject; for (EntityDescriptor descriptor : descriptors.getEntityDescriptors()) { if (descriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS) != null) { builders.add(convert(descriptor)); } } if (builders.isEmpty()) { throw new Saml2Exception("Metadata contains no IDPSSODescriptor elements"); } return builders; } if (xmlObject instanceof EntityDescriptor) { EntityDescriptor descriptor = (EntityDescriptor) xmlObject; return Arrays.asList(convert(descriptor)); } throw new Saml2Exception("Unsupported element of type " + xmlObject.getClass()); } private List<X509Certificate> certificates(KeyDescriptor keyDescriptor) { try { return KeyInfoSupport.getCertificates(keyDescriptor.getKeyInfo()); } catch (CertificateException ex) { throw new Saml2Exception(ex); } } private List<SigningMethod> signingMethods(IDPSSODescriptor idpssoDescriptor) { Extensions extensions = idpssoDescriptor.getExtensions(); List<SigningMethod> result = signingMethods(extensions); if (!result.isEmpty()) { return result; } EntityDescriptor descriptor = (EntityDescriptor) idpssoDescriptor.getParent(); extensions = descriptor.getExtensions(); return signingMethods(extensions); } private XMLObject xmlObject(InputStream inputStream) { Document document = document(inputStream); Element element = document.getDocumentElement(); Unmarshaller unmarshaller = this.registry.getUnmarshallerFactory().getUnmarshaller(element); if (unmarshaller == null) { throw new Saml2Exception("Unsupported element of type " + element.getTagName()); } try { return unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception(ex); } } private Document document(InputStream inputStream) { try { return this.parserPool.parse(inputStream); } catch (Exception ex) { throw new Saml2Exception(ex); } } private <T> List<T> signingMethods(Extensions extensions) { if (extensions != null) { return (List<T>) extensions.getUnknownXMLObjects(SigningMethod.DEFAULT_ELEMENT_NAME); } return new ArrayList<>(); } }
8,881
37.95614
104
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/registration/OpenSamlRelyingPartyRegistration.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.registration; import java.util.Collection; import java.util.function.Consumer; import org.opensaml.saml.saml2.metadata.EntityDescriptor; import org.springframework.security.saml2.core.Saml2X509Credential; /** * An OpenSAML implementation of {@link RelyingPartyRegistration} that contains OpenSAML * objects like {@link EntityDescriptor}. * * @author Josh Cummings * @since 6.1 */ public final class OpenSamlRelyingPartyRegistration extends RelyingPartyRegistration { OpenSamlRelyingPartyRegistration(RelyingPartyRegistration registration) { super(registration.getRegistrationId(), registration.getEntityId(), registration.getAssertionConsumerServiceLocation(), registration.getAssertionConsumerServiceBinding(), registration.getSingleLogoutServiceLocation(), registration.getSingleLogoutServiceResponseLocation(), registration.getSingleLogoutServiceBindings(), registration.getAssertingPartyDetails(), registration.getNameIdFormat(), registration.isAuthnRequestsSigned(), registration.getDecryptionX509Credentials(), registration.getSigningX509Credentials()); } /** * {@inheritDoc} */ @Override public OpenSamlRelyingPartyRegistration.Builder mutate() { OpenSamlAssertingPartyDetails party = getAssertingPartyDetails(); return withAssertingPartyEntityDescriptor(party.getEntityDescriptor()).registrationId(getRegistrationId()) .entityId(getEntityId()).signingX509Credentials((c) -> c.addAll(getSigningX509Credentials())) .decryptionX509Credentials((c) -> c.addAll(getDecryptionX509Credentials())) .assertionConsumerServiceLocation(getAssertionConsumerServiceLocation()) .assertionConsumerServiceBinding(getAssertionConsumerServiceBinding()) .singleLogoutServiceLocation(getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBindings((c) -> c.addAll(getSingleLogoutServiceBindings())) .nameIdFormat(getNameIdFormat()).authnRequestsSigned(isAuthnRequestsSigned()) .assertingPartyDetails((assertingParty) -> ((OpenSamlAssertingPartyDetails.Builder) assertingParty) .entityId(party.getEntityId()).wantAuthnRequestsSigned(party.getWantAuthnRequestsSigned()) .signingAlgorithms((algorithms) -> algorithms.addAll(party.getSigningAlgorithms())) .verificationX509Credentials((c) -> c.addAll(party.getVerificationX509Credentials())) .encryptionX509Credentials((c) -> c.addAll(party.getEncryptionX509Credentials())) .singleSignOnServiceLocation(party.getSingleSignOnServiceLocation()) .singleSignOnServiceBinding(party.getSingleSignOnServiceBinding()) .singleLogoutServiceLocation(party.getSingleLogoutServiceLocation()) .singleLogoutServiceResponseLocation(party.getSingleLogoutServiceResponseLocation()) .singleLogoutServiceBinding(party.getSingleLogoutServiceBinding())); } /** * {@inheritDoc} */ @Override public OpenSamlAssertingPartyDetails getAssertingPartyDetails() { return (OpenSamlAssertingPartyDetails) super.getAssertingPartyDetails(); } /** * Create a {@link Builder} from an entity descriptor * @param entityDescriptor the asserting party's {@link EntityDescriptor} * @return an {@link Builder} */ public static OpenSamlRelyingPartyRegistration.Builder withAssertingPartyEntityDescriptor( EntityDescriptor entityDescriptor) { return new Builder(entityDescriptor); } /** * An OpenSAML version of * {@link org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.AssertingPartyDetails.Builder} * that contains the underlying {@link EntityDescriptor} */ public static final class Builder extends RelyingPartyRegistration.Builder { private Builder(EntityDescriptor entityDescriptor) { super(entityDescriptor.getEntityID(), OpenSamlAssertingPartyDetails.withEntityDescriptor(entityDescriptor)); } @Override public Builder registrationId(String id) { return (Builder) super.registrationId(id); } public Builder entityId(String entityId) { return (Builder) super.entityId(entityId); } public Builder signingX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.signingX509Credentials(credentialsConsumer); } @Override public Builder decryptionX509Credentials(Consumer<Collection<Saml2X509Credential>> credentialsConsumer) { return (Builder) super.decryptionX509Credentials(credentialsConsumer); } @Override public Builder assertionConsumerServiceLocation(String assertionConsumerServiceLocation) { return (Builder) super.assertionConsumerServiceLocation(assertionConsumerServiceLocation); } @Override public Builder assertionConsumerServiceBinding(Saml2MessageBinding assertionConsumerServiceBinding) { return (Builder) super.assertionConsumerServiceBinding(assertionConsumerServiceBinding); } @Override public Builder singleLogoutServiceBinding(Saml2MessageBinding singleLogoutServiceBinding) { return singleLogoutServiceBindings((saml2MessageBindings) -> { saml2MessageBindings.clear(); saml2MessageBindings.add(singleLogoutServiceBinding); }); } @Override public Builder singleLogoutServiceBindings(Consumer<Collection<Saml2MessageBinding>> bindingsConsumer) { return (Builder) super.singleLogoutServiceBindings(bindingsConsumer); } @Override public Builder singleLogoutServiceLocation(String singleLogoutServiceLocation) { return (Builder) super.singleLogoutServiceLocation(singleLogoutServiceLocation); } public Builder singleLogoutServiceResponseLocation(String singleLogoutServiceResponseLocation) { return (Builder) super.singleLogoutServiceResponseLocation(singleLogoutServiceResponseLocation); } @Override public Builder nameIdFormat(String nameIdFormat) { return (Builder) super.nameIdFormat(nameIdFormat); } @Override public Builder authnRequestsSigned(Boolean authnRequestsSigned) { return (Builder) super.authnRequestsSigned(authnRequestsSigned); } @Override public Builder assertingPartyDetails(Consumer<AssertingPartyDetails.Builder> assertingPartyDetails) { return (Builder) super.assertingPartyDetails(assertingPartyDetails); } /** * Build an {@link OpenSamlRelyingPartyRegistration} * {@link org.springframework.security.saml2.provider.service.registration.OpenSamlRelyingPartyRegistration} * @return an {@link OpenSamlRelyingPartyRegistration} */ @Override public OpenSamlRelyingPartyRegistration build() { return new OpenSamlRelyingPartyRegistration(super.build()); } } }
7,282
39.91573
131
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationPlaceholderResolvers.java
/* * 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.util.HashMap; import java.util.Map; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.web.util.UrlUtils; import org.springframework.util.StringUtils; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; /** * A factory for creating placeholder resolvers for {@link RelyingPartyRegistration} * templates. Supports {@code baseUrl}, {@code baseScheme}, {@code baseHost}, * {@code basePort}, {@code basePath}, {@code registrationId}, * {@code relyingPartyEntityId}, and {@code assertingPartyEntityId} * * @author Josh Cummings * @since 6.1 */ public final class RelyingPartyRegistrationPlaceholderResolvers { private static final char PATH_DELIMITER = '/'; private RelyingPartyRegistrationPlaceholderResolvers() { } /** * Create a resolver based on the given {@link HttpServletRequest}. Given the request, * placeholders {@code baseUrl}, {@code baseScheme}, {@code baseHost}, * {@code basePort}, and {@code basePath} are resolved. * @param request the HTTP request * @return a resolver that can resolve {@code baseUrl}, {@code baseScheme}, * {@code baseHost}, {@code basePort}, and {@code basePath} placeholders */ public static UriResolver uriResolver(HttpServletRequest request) { return new UriResolver(uriVariables(request)); } /** * Create a resolver based on the given {@link HttpServletRequest}. Given the request, * placeholders {@code baseUrl}, {@code baseScheme}, {@code baseHost}, * {@code basePort}, {@code basePath}, {@code registrationId}, * {@code assertingPartyEntityId}, and {@code relyingPartyEntityId} are resolved. * @param request the HTTP request * @return a resolver that can resolve {@code baseUrl}, {@code baseScheme}, * {@code baseHost}, {@code basePort}, {@code basePath}, {@code registrationId}, * {@code relyingPartyEntityId}, and {@code assertingPartyEntityId} placeholders */ public static UriResolver uriResolver(HttpServletRequest request, RelyingPartyRegistration registration) { String relyingPartyEntityId = registration.getEntityId(); String assertingPartyEntityId = registration.getAssertingPartyDetails().getEntityId(); String registrationId = registration.getRegistrationId(); Map<String, String> uriVariables = uriVariables(request); uriVariables.put("relyingPartyEntityId", StringUtils.hasText(relyingPartyEntityId) ? relyingPartyEntityId : ""); uriVariables.put("assertingPartyEntityId", StringUtils.hasText(assertingPartyEntityId) ? assertingPartyEntityId : ""); uriVariables.put("entityId", StringUtils.hasText(assertingPartyEntityId) ? assertingPartyEntityId : ""); uriVariables.put("registrationId", StringUtils.hasText(registrationId) ? registrationId : ""); return new UriResolver(uriVariables); } private static Map<String, String> uriVariables(HttpServletRequest request) { String baseUrl = getApplicationUri(request); Map<String, String> uriVariables = new HashMap<>(); UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(baseUrl).replaceQuery(null).fragment(null) .build(); String scheme = uriComponents.getScheme(); uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); uriVariables.put("basePort", (port == -1) ? "" : ":" + port); String path = uriComponents.getPath(); if (StringUtils.hasLength(path) && path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); return uriVariables; } private static String getApplicationUri(HttpServletRequest request) { UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)) .replacePath(request.getContextPath()).replaceQuery(null).fragment(null).build(); return uriComponents.toUriString(); } /** * A class for resolving {@link RelyingPartyRegistration} URIs */ public static final class UriResolver { private final Map<String, String> uriVariables; private UriResolver(Map<String, String> uriVariables) { this.uriVariables = uriVariables; } public String resolve(String uri) { if (uri == null) { return null; } return UriComponentsBuilder.fromUriString(uri).buildAndExpand(this.uriVariables).toUriString(); } } }
5,363
40.261538
114
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/HttpSessionSaml2AuthenticationRequestRepository.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; /** * A {@link Saml2AuthenticationRequestRepository} implementation that uses * {@link HttpSession} to store and retrieve the * {@link AbstractSaml2AuthenticationRequest} * * @author Marcus Da Coregio * @since 5.6 */ public class HttpSessionSaml2AuthenticationRequestRepository implements Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> { private static final String DEFAULT_SAML2_AUTHN_REQUEST_ATTR_NAME = HttpSessionSaml2AuthenticationRequestRepository.class .getName().concat(".SAML2_AUTHN_REQUEST"); private String saml2AuthnRequestAttributeName = DEFAULT_SAML2_AUTHN_REQUEST_ATTR_NAME; @Override public AbstractSaml2AuthenticationRequest loadAuthenticationRequest(HttpServletRequest request) { HttpSession httpSession = request.getSession(false); if (httpSession == null) { return null; } return (AbstractSaml2AuthenticationRequest) httpSession.getAttribute(this.saml2AuthnRequestAttributeName); } @Override public void saveAuthenticationRequest(AbstractSaml2AuthenticationRequest authenticationRequest, HttpServletRequest request, HttpServletResponse response) { if (authenticationRequest == null) { removeAuthenticationRequest(request, response); return; } HttpSession httpSession = request.getSession(); httpSession.setAttribute(this.saml2AuthnRequestAttributeName, authenticationRequest); } @Override public AbstractSaml2AuthenticationRequest removeAuthenticationRequest(HttpServletRequest request, HttpServletResponse response) { AbstractSaml2AuthenticationRequest authenticationRequest = loadAuthenticationRequest(request); if (authenticationRequest == null) { return null; } HttpSession httpSession = request.getSession(); httpSession.removeAttribute(this.saml2AuthnRequestAttributeName); return authenticationRequest; } }
2,774
36.5
122
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/DefaultRelyingPartyRegistrationResolver.java
/* * 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.provider.service.web; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.convert.converter.Converter; 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.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * A {@link Converter} that resolves a {@link RelyingPartyRegistration} by extracting the * registration id from the request, querying a * {@link RelyingPartyRegistrationRepository}, and resolving any template values. * * @author Josh Cummings * @since 5.4 */ public final class DefaultRelyingPartyRegistrationResolver implements Converter<HttpServletRequest, RelyingPartyRegistration>, RelyingPartyRegistrationResolver { private Log logger = LogFactory.getLog(getClass()); private final RelyingPartyRegistrationRepository relyingPartyRegistrationRepository; private final RequestMatcher registrationRequestMatcher = new AntPathRequestMatcher("/**/{registrationId}"); public DefaultRelyingPartyRegistrationResolver( RelyingPartyRegistrationRepository relyingPartyRegistrationRepository) { Assert.notNull(relyingPartyRegistrationRepository, "relyingPartyRegistrationRepository cannot be null"); this.relyingPartyRegistrationRepository = relyingPartyRegistrationRepository; } /** * {@inheritDoc} */ @Override public RelyingPartyRegistration convert(HttpServletRequest request) { return resolve(request, null); } /** * {@inheritDoc} */ @Override public RelyingPartyRegistration resolve(HttpServletRequest request, String relyingPartyRegistrationId) { if (relyingPartyRegistrationId == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Attempting to resolve from " + this.registrationRequestMatcher + " since registrationId is null"); } relyingPartyRegistrationId = this.registrationRequestMatcher.matcher(request).getVariables() .get("registrationId"); } if (relyingPartyRegistrationId == null) { if (this.logger.isTraceEnabled()) { this.logger.trace("Returning null registration since registrationId is null"); } return null; } RelyingPartyRegistration registration = this.relyingPartyRegistrationRepository .findByRegistrationId(relyingPartyRegistrationId); if (registration == null) { return null; } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); return registration.mutate().entityId(uriResolver.resolve(registration.getEntityId())) .assertionConsumerServiceLocation( uriResolver.resolve(registration.getAssertionConsumerServiceLocation())) .singleLogoutServiceLocation(uriResolver.resolve(registration.getSingleLogoutServiceLocation())) .singleLogoutServiceResponseLocation( uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation())) .build(); } }
3,976
40
120
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/RelyingPartyRegistrationResolver.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; /** * A contract for resolving a {@link RelyingPartyRegistration} from the HTTP request * * @author Josh Cummings * @since 5.6 */ public interface RelyingPartyRegistrationResolver { /** * Resolve a {@link RelyingPartyRegistration} from the HTTP request, using the * {@code relyingPartyRegistrationId}, if it is provided * @param request the HTTP request * @param relyingPartyRegistrationId the {@link RelyingPartyRegistration} identifier * @return the resolved {@link RelyingPartyRegistration} */ RelyingPartyRegistration resolve(HttpServletRequest request, String relyingPartyRegistrationId); }
1,454
34.487805
97
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2MetadataFilter.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.provider.service.metadata.Saml2MetadataResolver; import org.springframework.security.saml2.provider.service.metadata.Saml2MetadataResponse; import org.springframework.security.saml2.provider.service.metadata.Saml2MetadataResponseResolver; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; /** * A {@link jakarta.servlet.Filter} that returns the metadata for a Relying Party * * @author Jakub Kubrynski * @author Josh Cummings * @since 5.4 */ public final class Saml2MetadataFilter extends OncePerRequestFilter { public static final String DEFAULT_METADATA_FILE_NAME = "saml-{registrationId}-metadata.xml"; private final Saml2MetadataResponseResolver metadataResolver; public Saml2MetadataFilter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver, Saml2MetadataResolver saml2MetadataResolver) { Assert.notNull(relyingPartyRegistrationResolver, "relyingPartyRegistrationResolver cannot be null"); Assert.notNull(saml2MetadataResolver, "saml2MetadataResolver cannot be null"); this.metadataResolver = new Saml2MetadataResponseResolverAdapter(relyingPartyRegistrationResolver, saml2MetadataResolver); } /** * Constructs an instance of {@link Saml2MetadataFilter} using the provided * parameters. The {@link #metadataResolver} field will be initialized with a * {@link DefaultRelyingPartyRegistrationResolver} instance using the provided * {@link RelyingPartyRegistrationRepository} * @param relyingPartyRegistrationRepository the * {@link RelyingPartyRegistrationRepository} to use * @param saml2MetadataResolver the {@link Saml2MetadataResolver} to use * @since 6.1 */ public Saml2MetadataFilter(RelyingPartyRegistrationRepository relyingPartyRegistrationRepository, Saml2MetadataResolver saml2MetadataResolver) { this(new DefaultRelyingPartyRegistrationResolver(relyingPartyRegistrationRepository), saml2MetadataResolver); } /** * Constructs an instance of {@link Saml2MetadataFilter} * @param metadataResponseResolver the strategy for producing metadata * @since 6.1 */ public Saml2MetadataFilter(Saml2MetadataResponseResolver metadataResponseResolver) { this.metadataResolver = metadataResponseResolver; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { Saml2MetadataResponse metadata; try { metadata = this.metadataResolver.resolve(request); } catch (Saml2Exception ex) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } if (metadata == null) { chain.doFilter(request, response); return; } writeMetadataToResponse(response, metadata); } private void writeMetadataToResponse(HttpServletResponse response, Saml2MetadataResponse metadata) throws IOException { response.setContentType(MediaType.APPLICATION_XML_VALUE); String format = "attachment; filename=\"%s\"; filename*=UTF-8''%s"; String fileName = metadata.getFileName(); String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()); response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format(format, fileName, encodedFileName)); response.setContentLength(metadata.getMetadata().length()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.getWriter().write(metadata.getMetadata()); } /** * Set the {@link RequestMatcher} that determines whether this filter should handle * the incoming {@link HttpServletRequest} * @param requestMatcher the {@link RequestMatcher} to identify requests for metadata */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); Assert.isInstanceOf(Saml2MetadataResponseResolverAdapter.class, this.metadataResolver, "a Saml2MetadataResponseResolver and RequestMatcher cannot be both set on this filter. Please set the request matcher on the Saml2MetadataResponseResolver itself."); ((Saml2MetadataResponseResolverAdapter) this.metadataResolver).setRequestMatcher(requestMatcher); } /** * Sets the metadata filename template containing the {@code {registrationId}} * template variable. * * <p> * The default value is {@code saml-{registrationId}-metadata.xml} * @param metadataFilename metadata filename, must contain a {registrationId} * @since 5.5 */ public void setMetadataFilename(String metadataFilename) { Assert.hasText(metadataFilename, "metadataFilename cannot be empty"); Assert.isTrue(metadataFilename.contains("{registrationId}"), "metadataFilename must contain a {registrationId} match variable"); Assert.isInstanceOf(Saml2MetadataResponseResolverAdapter.class, this.metadataResolver, "a Saml2MetadataResponseResolver and file name cannot be both set on this filter. Please set the file name on the Saml2MetadataResponseResolver itself."); ((Saml2MetadataResponseResolverAdapter) this.metadataResolver).setMetadataFilename(metadataFilename); } private static final class Saml2MetadataResponseResolverAdapter implements Saml2MetadataResponseResolver { private final RelyingPartyRegistrationResolver registrations; private RequestMatcher requestMatcher = new AntPathRequestMatcher( "/saml2/service-provider-metadata/{registrationId}"); private final Saml2MetadataResolver metadataResolver; private String metadataFilename = DEFAULT_METADATA_FILE_NAME; Saml2MetadataResponseResolverAdapter(RelyingPartyRegistrationResolver registrations, Saml2MetadataResolver metadataResolver) { this.registrations = registrations; this.metadataResolver = metadataResolver; } @Override public Saml2MetadataResponse resolve(HttpServletRequest request) { RequestMatcher.MatchResult matcher = this.requestMatcher.matcher(request); if (!matcher.isMatch()) { return null; } String registrationId = matcher.getVariables().get("registrationId"); RelyingPartyRegistration relyingPartyRegistration = this.registrations.resolve(request, registrationId); if (relyingPartyRegistration == null) { throw new Saml2Exception("registration not found"); } registrationId = relyingPartyRegistration.getRegistrationId(); String metadata = this.metadataResolver.resolve(relyingPartyRegistration); String fileName = this.metadataFilename.replace("{registrationId}", registrationId); return new Saml2MetadataResponse(metadata, fileName); } void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } void setMetadataFilename(String metadataFilename) { Assert.hasText(metadataFilename, "metadataFilename cannot be empty"); Assert.isTrue(metadataFilename.contains("{registrationId}"), "metadataFilename must contain a {registrationId} match variable"); this.metadataFilename = metadataFilename; } } }
8,471
42.446154
169
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationRequestRepository.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; /** * A repository for {@link AbstractSaml2AuthenticationRequest} * * @param <T> the type of SAML 2.0 Authentication Request * @author Marcus Da Coregio * @since 5.6 */ public interface Saml2AuthenticationRequestRepository<T extends AbstractSaml2AuthenticationRequest> { /** * Loads the {@link AbstractSaml2AuthenticationRequest} from the request * @param request the current request * @return the {@link AbstractSaml2AuthenticationRequest} or {@code null} if it is not * present */ T loadAuthenticationRequest(HttpServletRequest request); /** * Saves the current authentication request using the {@link HttpServletRequest} and * {@link HttpServletResponse} * @param authenticationRequest the {@link AbstractSaml2AuthenticationRequest} * @param request the current request * @param response the current response */ void saveAuthenticationRequest(T authenticationRequest, HttpServletRequest request, HttpServletResponse response); /** * Removes the authentication request using the {@link HttpServletRequest} and * {@link HttpServletResponse} * @param request the current request * @param response the current response * @return the removed {@link AbstractSaml2AuthenticationRequest} or {@code null} if * it is not present */ T removeAuthenticationRequest(HttpServletRequest request, HttpServletResponse response); }
2,266
36.163934
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/OpenSamlAuthenticationTokenConverter.java
/* * 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.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; 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; /** * 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 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 RelyingPartyRegistrationRepository registrations; private RequestMatcher requestMatcher = new OrRequestMatcher( new AntPathRequestMatcher("/login/saml2/sso/{registrationId}"), new AntPathRequestMatcher("/login/saml2/sso")); private final ParserPool parserPool; private final ResponseUnmarshaller unmarshaller; private Function<HttpServletRequest, AbstractSaml2AuthenticationRequest> loader; /** * Constructs a {@link OpenSamlAuthenticationTokenConverter} given a repository for * {@link RelyingPartyRegistration}s * @param registrations the repository for {@link RelyingPartyRegistration}s * {@link RelyingPartyRegistration}s */ 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; } /** * 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 = 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) { String serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); String decoded = new String(samlDecode(serialized), StandardCharsets.UTF_8); Response response = parse(decoded); 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 serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); String decoded = inflateIfRequired(request, samlDecode(serialized)); 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 */ public void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.loader = authenticationRequestRepository::loadAuthenticationRequest; } /** * 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.requestMatcher = requestMatcher; } private AbstractSaml2AuthenticationRequest loadAuthenticationRequest(HttpServletRequest request) { 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) { try { BASE_64_CHECKER.checkAcceptable(base64EncodedPayload); return BASE64.decode(base64EncodedPayload); } catch (Exception ex) { throw new Saml2AuthenticationException( new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Failed to decode SAMLResponse"), 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"); } } } }
12,238
37.731013
120
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2WebSsoAuthenticationRequestFilter.java
/* * 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 jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.MediaType; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.web.authentication.Saml2AuthenticationRequestResolver; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * This {@code Filter} formulates a * <a href="https://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf">SAML 2.0 * AuthnRequest</a> (line 1968) and redirects to a configured asserting party. * * <p> * It supports the <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf">HTTP-Redirect</a> * (line 520) and <a href= * "https://docs.oasis-open.org/security/saml/v2.0/saml-bindings-2.0-os.pdf">HTTP-POST</a> * (line 753) bindings. * * <p> * By default, this {@code Filter} responds to authentication requests at the {@code URI} * {@code /saml2/authenticate/{registrationId}}. The {@code URI} template variable * {@code {registrationId}} represents the * {@link RelyingPartyRegistration#getRegistrationId() registration identifier} of the * relying party that is used for initiating the authentication request. * * @author Filip Hanik * @author Josh Cummings * @since 5.2 */ public class Saml2WebSsoAuthenticationRequestFilter extends OncePerRequestFilter { private final Saml2AuthenticationRequestResolver authenticationRequestResolver; private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = new HttpSessionSaml2AuthenticationRequestRepository(); /** * Construct a {@link Saml2WebSsoAuthenticationRequestFilter} with the strategy for * resolving the {@code AuthnRequest} * @param authenticationRequestResolver the strategy for resolving the * {@code AuthnRequest} * @since 5.7 */ public Saml2WebSsoAuthenticationRequestFilter(Saml2AuthenticationRequestResolver authenticationRequestResolver) { Assert.notNull(authenticationRequestResolver, "authenticationRequestResolver cannot be null"); this.authenticationRequestResolver = authenticationRequestResolver; } /** * Use the given {@link Saml2AuthenticationRequestRepository} to save the * authentication request * @param authenticationRequestRepository the * {@link Saml2AuthenticationRequestRepository} to use * @since 5.6 */ public void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.authenticationRequestRepository = authenticationRequestRepository; } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestResolver.resolve(request); if (authenticationRequest == null) { filterChain.doFilter(request, response); return; } if (authenticationRequest instanceof Saml2RedirectAuthenticationRequest) { sendRedirect(request, response, (Saml2RedirectAuthenticationRequest) authenticationRequest); } else { sendPost(request, response, (Saml2PostAuthenticationRequest) authenticationRequest); } } private void sendRedirect(HttpServletRequest request, HttpServletResponse response, Saml2RedirectAuthenticationRequest authenticationRequest) throws IOException { this.authenticationRequestRepository.saveAuthenticationRequest(authenticationRequest, request, response); UriComponentsBuilder uriBuilder = UriComponentsBuilder .fromUriString(authenticationRequest.getAuthenticationRequestUri()); addParameter(Saml2ParameterNames.SAML_REQUEST, authenticationRequest.getSamlRequest(), uriBuilder); addParameter(Saml2ParameterNames.RELAY_STATE, authenticationRequest.getRelayState(), uriBuilder); addParameter(Saml2ParameterNames.SIG_ALG, authenticationRequest.getSigAlg(), uriBuilder); addParameter(Saml2ParameterNames.SIGNATURE, authenticationRequest.getSignature(), uriBuilder); String redirectUrl = uriBuilder.build(true).toUriString(); response.sendRedirect(redirectUrl); } private void addParameter(String name, String value, UriComponentsBuilder builder) { Assert.hasText(name, "name cannot be empty or null"); if (StringUtils.hasText(value)) { builder.queryParam(UriUtils.encode(name, StandardCharsets.ISO_8859_1), UriUtils.encode(value, StandardCharsets.ISO_8859_1)); } } private void sendPost(HttpServletRequest request, HttpServletResponse response, Saml2PostAuthenticationRequest authenticationRequest) throws IOException { this.authenticationRequestRepository.saveAuthenticationRequest(authenticationRequest, request, response); String html = createSamlPostRequestFormData(authenticationRequest); response.setContentType(MediaType.TEXT_HTML_VALUE); response.getWriter().write(html); } private String createSamlPostRequestFormData(Saml2PostAuthenticationRequest authenticationRequest) { String authenticationRequestUri = authenticationRequest.getAuthenticationRequestUri(); String relayState = authenticationRequest.getRelayState(); String samlRequest = authenticationRequest.getSamlRequest(); StringBuilder html = new StringBuilder(); html.append("<!DOCTYPE html>\n"); html.append("<html>\n").append(" <head>\n"); html.append(" <meta http-equiv=\"Content-Security-Policy\" ") .append("content=\"script-src 'sha256-oZhLbc2kO8b8oaYLrUc7uye1MgVKMyLtPqWR4WtKF+c='\">\n"); html.append(" <meta charset=\"utf-8\" />\n"); html.append(" </head>\n"); html.append(" <body>\n"); html.append(" <noscript>\n"); html.append(" <p>\n"); html.append(" <strong>Note:</strong> Since your browser does not support JavaScript,\n"); html.append(" you must press the Continue button once to proceed.\n"); html.append(" </p>\n"); html.append(" </noscript>\n"); html.append(" \n"); html.append(" <form action=\""); html.append(authenticationRequestUri); html.append("\" method=\"post\">\n"); html.append(" <div>\n"); html.append(" <input type=\"hidden\" name=\"SAMLRequest\" value=\""); html.append(HtmlUtils.htmlEscape(samlRequest)); html.append("\"/>\n"); if (StringUtils.hasText(relayState)) { html.append(" <input type=\"hidden\" name=\"RelayState\" value=\""); html.append(HtmlUtils.htmlEscape(relayState)); html.append("\"/>\n"); } html.append(" </div>\n"); html.append(" <noscript>\n"); html.append(" <div>\n"); html.append(" <input type=\"submit\" value=\"Continue\"/>\n"); html.append(" </div>\n"); html.append(" </noscript>\n"); html.append(" </form>\n"); html.append(" \n"); html.append(" <script>window.onload = function() { document.forms[0].submit(); }</script>\n"); html.append(" </body>\n"); html.append("</html>"); return html.toString(); } }
8,762
46.112903
170
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/Saml2AuthenticationTokenConverter.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web; 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 org.springframework.http.HttpMethod; 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.web.authentication.AuthenticationConverter; 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 5.4 */ 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; /** * Constructs a {@link Saml2AuthenticationTokenConverter} given a strategy for * resolving {@link RelyingPartyRegistration}s * @param relyingPartyRegistrationResolver the strategy for resolving * {@link RelyingPartyRegistration}s */ public Saml2AuthenticationTokenConverter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { Assert.notNull(relyingPartyRegistrationResolver, "relyingPartyRegistrationResolver cannot be null"); this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; this.loader = new HttpSessionSaml2AuthenticationRequestRepository()::loadAuthenticationRequest; } @Override public Saml2AuthenticationToken convert(HttpServletRequest request) { AbstractSaml2AuthenticationRequest authenticationRequest = loadAuthenticationRequest(request); String relyingPartyRegistrationId = (authenticationRequest != null) ? authenticationRequest.getRelyingPartyRegistrationId() : null; RelyingPartyRegistration relyingPartyRegistration = this.relyingPartyRegistrationResolver.resolve(request, relyingPartyRegistrationId); if (relyingPartyRegistration == null) { return null; } String saml2Response = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); if (saml2Response == null) { return null; } byte[] b = samlDecode(saml2Response); saml2Response = inflateIfRequired(request, b); return new Saml2AuthenticationToken(relyingPartyRegistration, saml2Response, authenticationRequest); } /** * Use the given {@link Saml2AuthenticationRequestRepository} to load authentication * request. * @param authenticationRequestRepository the * {@link Saml2AuthenticationRequestRepository} to use * @since 5.6 */ public void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.loader = authenticationRequestRepository::loadAuthenticationRequest; } private AbstractSaml2AuthenticationRequest loadAuthenticationRequest(HttpServletRequest request) { 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) { try { BASE_64_CHECKER.checkAcceptable(base64EncodedPayload); return BASE64.decode(base64EncodedPayload); } catch (Exception ex) { throw new Saml2AuthenticationException( new Saml2Error(Saml2ErrorCodes.INVALID_RESPONSE, "Failed to decode SAMLResponse"), 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"); } } } }
7,014
34.974359
110
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/Saml2Utils.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; 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); } } }
2,206
27.662338
102
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSamlSigningUtils.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.Marshaller; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; import org.opensaml.security.SecurityException; import org.opensaml.security.credential.BasicCredential; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.SignatureSigningParameters; import org.opensaml.xmlsec.SignatureSigningParametersResolver; import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; import org.opensaml.xmlsec.crypto.XMLSigningUtil; import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; import org.opensaml.xmlsec.signature.SignableXMLObject; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.opensaml.xmlsec.signature.support.SignatureSupport; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * Utility methods for signing SAML components with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlSigningUtils { static String serialize(XMLObject object) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } static <O extends SignableXMLObject> O sign(O object, RelyingPartyRegistration relyingPartyRegistration) { SignatureSigningParameters parameters = resolveSigningParameters(relyingPartyRegistration); try { SignatureSupport.signObject(object, parameters); return object; } catch (Exception ex) { throw new Saml2Exception(ex); } } static QueryParametersPartial sign(RelyingPartyRegistration registration) { return new QueryParametersPartial(registration); } private static SignatureSigningParameters resolveSigningParameters( RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = resolveSigningCredentials(relyingPartyRegistration); List<String> algorithms = relyingPartyRegistration.getAssertingPartyDetails().getSigningAlgorithms(); List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); CriteriaSet criteria = new CriteriaSet(); BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); signingConfiguration.setSigningCredentials(credentials); signingConfiguration.setSignatureAlgorithms(algorithms); signingConfiguration.setSignatureReferenceDigestMethods(digests); signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); criteria.add(new SignatureSigningConfigurationCriterion(signingConfiguration)); try { SignatureSigningParameters parameters = resolver.resolveSingle(criteria); Assert.notNull(parameters, "Failed to resolve any signing credential"); return parameters; } catch (Exception ex) { throw new Saml2Exception(ex); } } private static NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); namedManager.setUseDefaultManager(true); final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); // Generator for X509Credentials final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); x509Factory.setEmitEntityCertificate(true); x509Factory.setEmitEntityCertificateChain(true); defaultManager.registerFactory(x509Factory); return namedManager; } private static List<Credential> resolveSigningCredentials(RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = new ArrayList<>(); for (Saml2X509Credential x509Credential : relyingPartyRegistration.getSigningX509Credentials()) { X509Certificate certificate = x509Credential.getCertificate(); PrivateKey privateKey = x509Credential.getPrivateKey(); BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); credential.setEntityId(relyingPartyRegistration.getEntityId()); credential.setUsageType(UsageType.SIGNING); credentials.add(credential); } return credentials; } private OpenSamlSigningUtils() { } static class QueryParametersPartial { final RelyingPartyRegistration registration; final Map<String, String> components = new LinkedHashMap<>(); QueryParametersPartial(RelyingPartyRegistration registration) { this.registration = registration; } QueryParametersPartial param(String key, String value) { this.components.put(key, value); return this; } Map<String, String> parameters() { SignatureSigningParameters parameters = resolveSigningParameters(this.registration); Credential credential = parameters.getSigningCredential(); String algorithmUri = parameters.getSignatureAlgorithm(); this.components.put("SigAlg", 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("Signature", b64Signature); } catch (SecurityException ex) { throw new Saml2Exception(ex); } return this.components; } } }
7,835
39.391753
111
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSaml4AuthenticationRequestResolver.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.time.Clock; import java.time.Instant; import java.util.function.Consumer; import jakarta.servlet.http.HttpServletRequest; import org.opensaml.saml.saml2.core.AuthnRequest; import org.springframework.core.convert.converter.Converter; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * A strategy for resolving a SAML 2.0 Authentication Request from the * {@link HttpServletRequest} using OpenSAML. * * @author Josh Cummings * @since 5.7 */ public final class OpenSaml4AuthenticationRequestResolver implements Saml2AuthenticationRequestResolver { private final OpenSamlAuthenticationRequestResolver authnRequestResolver; private Consumer<AuthnRequestContext> contextConsumer = (parameters) -> { }; private Clock clock = Clock.systemUTC(); /** * Construct an {@link OpenSaml4AuthenticationRequestResolver} * @param registrations a repository for relying and asserting party configuration * @since 6.1 */ public OpenSaml4AuthenticationRequestResolver(RelyingPartyRegistrationRepository registrations) { this.authnRequestResolver = new OpenSamlAuthenticationRequestResolver((request, id) -> { if (id == null) { return null; } return registrations.findByRegistrationId(id); }); } /** * Construct a {@link OpenSaml4AuthenticationRequestResolver} */ public OpenSaml4AuthenticationRequestResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { this.authnRequestResolver = new OpenSamlAuthenticationRequestResolver(relyingPartyRegistrationResolver); } @Override public <T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request) { return this.authnRequestResolver.resolve(request, (registration, authnRequest) -> { authnRequest.setIssueInstant(Instant.now(this.clock)); this.contextConsumer.accept(new AuthnRequestContext(request, registration, authnRequest)); }); } /** * Set a {@link Consumer} for modifying the OpenSAML {@link AuthnRequest} * @param contextConsumer a consumer that accepts an {@link AuthnRequestContext} */ public void setAuthnRequestCustomizer(Consumer<AuthnRequestContext> contextConsumer) { Assert.notNull(contextConsumer, "contextConsumer cannot be null"); this.contextConsumer = contextConsumer; } /** * Set the {@link RequestMatcher} to use for setting the * {@link OpenSamlAuthenticationRequestResolver#setRequestMatcher(RequestMatcher)} * (RequestMatcher)} * @param requestMatcher the {@link RequestMatcher} to identify authentication * requests. * @since 5.8 */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.authnRequestResolver.setRequestMatcher(requestMatcher); } /** * Use this {@link Clock} for generating the issued {@link Instant} * @param clock the {@link Clock} to use */ public void setClock(Clock clock) { Assert.notNull(clock, "clock must not be null"); this.clock = clock; } /** * Use this {@link Converter} to compute the RelayState * @param relayStateResolver the {@link Converter} to use * @since 5.8 */ public void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { Assert.notNull(relayStateResolver, "relayStateResolver cannot be null"); this.authnRequestResolver.setRelayStateResolver(relayStateResolver); } public static final class AuthnRequestContext { private final HttpServletRequest request; private final RelyingPartyRegistration registration; private final AuthnRequest authnRequest; public AuthnRequestContext(HttpServletRequest request, RelyingPartyRegistration registration, AuthnRequest authnRequest) { this.request = request; this.registration = registration; this.authnRequest = authnRequest; } public HttpServletRequest getRequest() { return this.request; } public RelyingPartyRegistration getRelyingPartyRegistration() { return this.registration; } public AuthnRequest getAuthnRequest() { return this.authnRequest; } } }
5,223
33.826667
115
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSamlVerificationUtils.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import org.opensaml.core.criterion.EntityIdCriterion; import org.opensaml.saml.common.xml.SAMLConstants; import org.opensaml.saml.criterion.ProtocolCriterion; import org.opensaml.saml.metadata.criteria.role.impl.EvaluableProtocolRoleDescriptorCriterion; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.RequestAbstractType; import org.opensaml.saml.saml2.core.StatusResponseType; import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialResolver; 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.config.impl.DefaultSecurityConfigurationBootstrap; import org.opensaml.xmlsec.signature.Signature; import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; import org.opensaml.xmlsec.signature.support.impl.ExplicitKeySignatureTrustEngine; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ResponseValidatorResult; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.web.util.UriUtils; /** * Utility methods for verifying SAML component signatures with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlVerificationUtils { static VerifierPartial verifySignature(StatusResponseType object, RelyingPartyRegistration registration) { return new VerifierPartial(object, registration); } static VerifierPartial verifySignature(RequestAbstractType object, RelyingPartyRegistration registration) { return new VerifierPartial(object, registration); } private OpenSamlVerificationUtils() { } static class VerifierPartial { private final String id; private final CriteriaSet criteria; private final SignatureTrustEngine trustEngine; VerifierPartial(StatusResponseType object, RelyingPartyRegistration registration) { this.id = object.getID(); this.criteria = verificationCriteria(object.getIssuer()); this.trustEngine = trustEngine(registration); } VerifierPartial(RequestAbstractType object, RelyingPartyRegistration registration) { this.id = object.getID(); this.criteria = verificationCriteria(object.getIssuer()); this.trustEngine = trustEngine(registration); } Saml2ResponseValidatorResult redirect(HttpServletRequest request, String objectParameterName) { RedirectSignature signature = new RedirectSignature(request, objectParameterName); if (signature.getAlgorithm() == null) { return Saml2ResponseValidatorResult.failure(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Missing signature algorithm for object [" + this.id + "]")); } if (!signature.hasSignature()) { return Saml2ResponseValidatorResult.failure(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Missing signature for object [" + this.id + "]")); } Collection<Saml2Error> errors = new ArrayList<>(); String algorithmUri = signature.getAlgorithm(); try { if (!this.trustEngine.validate(signature.getSignature(), signature.getContent(), algorithmUri, this.criteria, null)) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]")); } } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } return Saml2ResponseValidatorResult.failure(errors); } Saml2ResponseValidatorResult post(Signature signature) { 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 [" + this.id + "]: ")); } try { if (!this.trustEngine.validate(signature, this.criteria)) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]")); } } catch (Exception ex) { errors.add(new Saml2Error(Saml2ErrorCodes.INVALID_SIGNATURE, "Invalid signature for object [" + this.id + "]: ")); } return Saml2ResponseValidatorResult.failure(errors); } private CriteriaSet verificationCriteria(Issuer issuer) { CriteriaSet criteria = new CriteriaSet(); criteria.add(new EvaluableEntityIDCredentialCriterion(new EntityIdCriterion(issuer.getValue()))); criteria.add(new EvaluableProtocolRoleDescriptorCriterion(new ProtocolCriterion(SAMLConstants.SAML20P_NS))); criteria.add(new EvaluableUsageCredentialCriterion(new UsageCriterion(UsageType.SIGNING))); return criteria; } private SignatureTrustEngine trustEngine(RelyingPartyRegistration registration) { Set<Credential> credentials = new HashSet<>(); Collection<Saml2X509Credential> keys = registration.getAssertingPartyDetails() .getVerificationX509Credentials(); for (Saml2X509Credential key : keys) { BasicX509Credential cred = new BasicX509Credential(key.getCertificate()); cred.setUsageType(UsageType.SIGNING); cred.setEntityId(registration.getAssertingPartyDetails().getEntityId()); credentials.add(cred); } CredentialResolver credentialsResolver = new CollectionCredentialResolver(credentials); return new ExplicitKeySignatureTrustEngine(credentialsResolver, DefaultSecurityConfigurationBootstrap.buildBasicInlineKeyInfoCredentialResolver()); } private static class RedirectSignature { private final HttpServletRequest request; private final String objectParameterName; RedirectSignature(HttpServletRequest request, String objectParameterName) { this.request = request; this.objectParameterName = objectParameterName; } String getAlgorithm() { return this.request.getParameter("SigAlg"); } byte[] getContent() { String query = String.format("%s=%s&SigAlg=%s", this.objectParameterName, UriUtils.encode(this.request.getParameter(this.objectParameterName), StandardCharsets.ISO_8859_1), UriUtils.encode(getAlgorithm(), StandardCharsets.ISO_8859_1)); return query.getBytes(StandardCharsets.UTF_8); } byte[] getSignature() { return Saml2Utils.samlDecode(this.request.getParameter("Signature")); } boolean hasSignature() { return this.request.getParameter("Signature") != null; } } } }
8,016
37.729469
111
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/Saml2WebSsoAuthenticationFilter.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; 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.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.web.DefaultRelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.HttpSessionSaml2AuthenticationRequestRepository; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationRequestRepository; import org.springframework.security.saml2.provider.service.web.Saml2AuthenticationTokenConverter; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.authentication.AuthenticationConverter; import org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy; import org.springframework.util.Assert; /** * @since 5.2 */ public class Saml2WebSsoAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public static final String DEFAULT_FILTER_PROCESSES_URI = "/login/saml2/sso/{registrationId}"; private final AuthenticationConverter authenticationConverter; private Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository = new HttpSessionSaml2AuthenticationRequestRepository(); /** * Creates a {@code Saml2WebSsoAuthenticationFilter} authentication filter that is * configured to use the {@link #DEFAULT_FILTER_PROCESSES_URI} processing URL * @param relyingPartyRegistrationRepository - repository of configured SAML 2 * entities. Required. */ public Saml2WebSsoAuthenticationFilter(RelyingPartyRegistrationRepository relyingPartyRegistrationRepository) { this(relyingPartyRegistrationRepository, DEFAULT_FILTER_PROCESSES_URI); } /** * Creates a {@code Saml2WebSsoAuthenticationFilter} authentication filter * @param relyingPartyRegistrationRepository - repository of configured SAML 2 * entities. Required. * @param filterProcessesUrl the processing URL, must contain a {registrationId} * variable. Required. */ public Saml2WebSsoAuthenticationFilter(RelyingPartyRegistrationRepository relyingPartyRegistrationRepository, String filterProcessesUrl) { this(new Saml2AuthenticationTokenConverter( (RelyingPartyRegistrationResolver) new DefaultRelyingPartyRegistrationResolver( relyingPartyRegistrationRepository)), filterProcessesUrl); Assert.isTrue(filterProcessesUrl.contains("{registrationId}"), "filterProcessesUrl must contain a {registrationId} match variable"); } /** * Creates a {@link Saml2WebSsoAuthenticationFilter} given the provided parameters * @param authenticationConverter the strategy for converting an * {@link HttpServletRequest} into an {@link Authentication} * @param filterProcessesUrl the processing URL * @since 5.4 */ public Saml2WebSsoAuthenticationFilter(AuthenticationConverter authenticationConverter, String filterProcessesUrl) { super(filterProcessesUrl); Assert.notNull(authenticationConverter, "authenticationConverter cannot be null"); Assert.hasText(filterProcessesUrl, "filterProcessesUrl must contain a URL pattern"); this.authenticationConverter = authenticationConverter; setAllowSessionCreation(true); setSessionAuthenticationStrategy(new ChangeSessionIdAuthenticationStrategy()); } @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { return super.requiresAuthentication(request, response); } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { Authentication authentication = this.authenticationConverter.convert(request); if (authentication == null) { Saml2Error saml2Error = new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "No relying party registration found"); throw new Saml2AuthenticationException(saml2Error); } setDetails(request, authentication); this.authenticationRequestRepository.removeAuthenticationRequest(request, response); return getAuthenticationManager().authenticate(authentication); } /** * Use the given {@link Saml2AuthenticationRequestRepository} to remove the saved * authentication request. If the {@link #authenticationConverter} is of the type * {@link Saml2AuthenticationTokenConverter}, the * {@link Saml2AuthenticationRequestRepository} will also be set into the * {@link #authenticationConverter}. * @param authenticationRequestRepository the * {@link Saml2AuthenticationRequestRepository} to use * @since 5.6 */ public void setAuthenticationRequestRepository( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null"); this.authenticationRequestRepository = authenticationRequestRepository; setAuthenticationRequestRepositoryIntoAuthenticationConverter(authenticationRequestRepository); } private void setAuthenticationRequestRepositoryIntoAuthenticationConverter( Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) { if (this.authenticationConverter instanceof Saml2AuthenticationTokenConverter authenticationTokenConverter) { authenticationTokenConverter.setAuthenticationRequestRepository(authenticationRequestRepository); } } private void setDetails(HttpServletRequest request, Authentication authentication) { if (AbstractAuthenticationToken.class.isAssignableFrom(authentication.getClass())) { Object details = this.authenticationDetailsSource.buildDetails(request); ((AbstractAuthenticationToken) authentication).setDetails(details); } } }
7,229
48.862069
170
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/OpenSamlAuthenticationRequestResolver.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.UUID; import java.util.function.BiConsumer; import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.saml.saml2.core.AuthnRequest; import org.opensaml.saml.saml2.core.Issuer; import org.opensaml.saml.saml2.core.NameID; import org.opensaml.saml.saml2.core.NameIDPolicy; import org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder; import org.opensaml.saml.saml2.core.impl.AuthnRequestMarshaller; import org.opensaml.saml.saml2.core.impl.IssuerBuilder; import org.opensaml.saml.saml2.core.impl.NameIDBuilder; import org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder; import org.w3c.dom.Element; import org.springframework.core.convert.converter.Converter; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2PostAuthenticationRequest; import org.springframework.security.saml2.provider.service.authentication.Saml2RedirectAuthenticationRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * For internal use only. Intended for consolidating common behavior related to minting a * SAML 2.0 Authn Request. */ class OpenSamlAuthenticationRequestResolver { static { OpenSamlInitializationService.initialize(); } private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; private final AuthnRequestBuilder authnRequestBuilder; private final AuthnRequestMarshaller marshaller; private final IssuerBuilder issuerBuilder; private final NameIDBuilder nameIdBuilder; private final NameIDPolicyBuilder nameIdPolicyBuilder; private RequestMatcher requestMatcher = new AntPathRequestMatcher( Saml2AuthenticationRequestResolver.DEFAULT_AUTHENTICATION_REQUEST_URI); private Converter<HttpServletRequest, String> relayStateResolver = (request) -> UUID.randomUUID().toString(); /** * Construct a {@link OpenSamlAuthenticationRequestResolver} using the provided * parameters * @param relyingPartyRegistrationResolver a strategy for resolving the * {@link RelyingPartyRegistration} from the {@link HttpServletRequest} */ OpenSamlAuthenticationRequestResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { Assert.notNull(relyingPartyRegistrationResolver, "relyingPartyRegistrationResolver cannot be null"); this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.marshaller = (AuthnRequestMarshaller) registry.getMarshallerFactory() .getMarshaller(AuthnRequest.DEFAULT_ELEMENT_NAME); Assert.notNull(this.marshaller, "logoutRequestMarshaller must be configured in OpenSAML"); this.authnRequestBuilder = (AuthnRequestBuilder) XMLObjectProviderRegistrySupport.getBuilderFactory() .getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME); Assert.notNull(this.authnRequestBuilder, "authnRequestBuilder must be configured in OpenSAML"); this.issuerBuilder = (IssuerBuilder) registry.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME); Assert.notNull(this.issuerBuilder, "issuerBuilder must be configured in OpenSAML"); this.nameIdBuilder = (NameIDBuilder) registry.getBuilderFactory().getBuilder(NameID.DEFAULT_ELEMENT_NAME); Assert.notNull(this.nameIdBuilder, "nameIdBuilder must be configured in OpenSAML"); this.nameIdPolicyBuilder = (NameIDPolicyBuilder) registry.getBuilderFactory() .getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME); Assert.notNull(this.nameIdPolicyBuilder, "nameIdPolicyBuilder must be configured in OpenSAML"); } void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { this.relayStateResolver = relayStateResolver; } void setRequestMatcher(RequestMatcher requestMatcher) { this.requestMatcher = requestMatcher; } <T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request) { return resolve(request, (registration, logoutRequest) -> { }); } <T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request, BiConsumer<RelyingPartyRegistration, AuthnRequest> authnRequestConsumer) { RequestMatcher.MatchResult result = this.requestMatcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = result.getVariables().get("registrationId"); RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, registrationId); if (registration == null) { return null; } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); String assertionConsumerServiceLocation = uriResolver .resolve(registration.getAssertionConsumerServiceLocation()); AuthnRequest authnRequest = this.authnRequestBuilder.buildObject(); authnRequest.setForceAuthn(Boolean.FALSE); authnRequest.setIsPassive(Boolean.FALSE); authnRequest.setProtocolBinding(registration.getAssertionConsumerServiceBinding().getUrn()); Issuer iss = this.issuerBuilder.buildObject(); iss.setValue(entityId); authnRequest.setIssuer(iss); authnRequest.setDestination(registration.getAssertingPartyDetails().getSingleSignOnServiceLocation()); authnRequest.setAssertionConsumerServiceURL(assertionConsumerServiceLocation); if (registration.getNameIdFormat() != null) { NameIDPolicy nameIdPolicy = this.nameIdPolicyBuilder.buildObject(); nameIdPolicy.setFormat(registration.getNameIdFormat()); authnRequest.setNameIDPolicy(nameIdPolicy); } authnRequestConsumer.accept(registration, authnRequest); if (authnRequest.getID() == null) { authnRequest.setID("ARQ" + UUID.randomUUID().toString().substring(1)); } String relayState = this.relayStateResolver.convert(request); Saml2MessageBinding binding = registration.getAssertingPartyDetails().getSingleSignOnServiceBinding(); if (binding == Saml2MessageBinding.POST) { if (registration.getAssertingPartyDetails().getWantAuthnRequestsSigned() || registration.isAuthnRequestsSigned()) { OpenSamlSigningUtils.sign(authnRequest, registration); } String xml = serialize(authnRequest); String encoded = Saml2Utils.samlEncode(xml.getBytes(StandardCharsets.UTF_8)); return (T) Saml2PostAuthenticationRequest.withRelyingPartyRegistration(registration).samlRequest(encoded) .relayState(relayState).id(authnRequest.getID()).build(); } else { String xml = serialize(authnRequest); String deflatedAndEncoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(xml)); Saml2RedirectAuthenticationRequest.Builder builder = Saml2RedirectAuthenticationRequest .withRelyingPartyRegistration(registration).samlRequest(deflatedAndEncoded).relayState(relayState) .id(authnRequest.getID()); if (registration.getAssertingPartyDetails().getWantAuthnRequestsSigned() || registration.isAuthnRequestsSigned()) { Map<String, String> parameters = OpenSamlSigningUtils.sign(registration) .param(Saml2ParameterNames.SAML_REQUEST, deflatedAndEncoded) .param(Saml2ParameterNames.RELAY_STATE, relayState).parameters(); builder.sigAlg(parameters.get(Saml2ParameterNames.SIG_ALG)) .signature(parameters.get(Saml2ParameterNames.SIGNATURE)); } return (T) builder.build(); } } private String serialize(AuthnRequest authnRequest) { try { Element element = this.marshaller.marshall(authnRequest); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } }
9,566
48.061538
120
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/Saml2AuthenticationRequestResolver.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication; import jakarta.servlet.http.HttpServletRequest; import org.springframework.security.saml2.provider.service.authentication.AbstractSaml2AuthenticationRequest; /** * A strategy for resolving a SAML 2.0 Authentication Request from the * {@link HttpServletRequest}. * * @author Josh Cummings * @since 5.7 */ public interface Saml2AuthenticationRequestResolver { String DEFAULT_AUTHENTICATION_REQUEST_URI = "/saml2/authenticate/{registrationId}"; <T extends AbstractSaml2AuthenticationRequest> T resolve(HttpServletRequest request); }
1,247
32.72973
109
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2Utils.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; 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); } } }
2,213
27.753247
102
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlSigningUtils.java
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.nio.charset.StandardCharsets; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import net.shibboleth.utilities.java.support.resolver.CriteriaSet; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.opensaml.core.xml.XMLObject; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.Marshaller; import org.opensaml.core.xml.io.MarshallingException; import org.opensaml.saml.security.impl.SAMLMetadataSignatureSigningParametersResolver; import org.opensaml.security.SecurityException; import org.opensaml.security.credential.BasicCredential; import org.opensaml.security.credential.Credential; import org.opensaml.security.credential.CredentialSupport; import org.opensaml.security.credential.UsageType; import org.opensaml.xmlsec.SignatureSigningParameters; import org.opensaml.xmlsec.SignatureSigningParametersResolver; import org.opensaml.xmlsec.criterion.SignatureSigningConfigurationCriterion; import org.opensaml.xmlsec.crypto.XMLSigningUtil; import org.opensaml.xmlsec.impl.BasicSignatureSigningConfiguration; import org.opensaml.xmlsec.keyinfo.KeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.NamedKeyInfoGeneratorManager; import org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory; import org.opensaml.xmlsec.signature.SignableXMLObject; import org.opensaml.xmlsec.signature.support.SignatureConstants; import org.opensaml.xmlsec.signature.support.SignatureSupport; import org.w3c.dom.Element; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.core.Saml2X509Credential; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.util.Assert; import org.springframework.web.util.UriComponentsBuilder; import org.springframework.web.util.UriUtils; /** * Utility methods for signing SAML components with OpenSAML * * For internal use only. * * @author Josh Cummings */ final class OpenSamlSigningUtils { static String serialize(XMLObject object) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(object); Element element = marshaller.marshall(object); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } static <O extends SignableXMLObject> O sign(O object, RelyingPartyRegistration relyingPartyRegistration) { SignatureSigningParameters parameters = resolveSigningParameters(relyingPartyRegistration); try { SignatureSupport.signObject(object, parameters); return object; } catch (Exception ex) { throw new Saml2Exception(ex); } } static QueryParametersPartial sign(RelyingPartyRegistration registration) { return new QueryParametersPartial(registration); } private static SignatureSigningParameters resolveSigningParameters( RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = resolveSigningCredentials(relyingPartyRegistration); List<String> algorithms = relyingPartyRegistration.getAssertingPartyDetails().getSigningAlgorithms(); List<String> digests = Collections.singletonList(SignatureConstants.ALGO_ID_DIGEST_SHA256); String canonicalization = SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; SignatureSigningParametersResolver resolver = new SAMLMetadataSignatureSigningParametersResolver(); CriteriaSet criteria = new CriteriaSet(); BasicSignatureSigningConfiguration signingConfiguration = new BasicSignatureSigningConfiguration(); signingConfiguration.setSigningCredentials(credentials); signingConfiguration.setSignatureAlgorithms(algorithms); signingConfiguration.setSignatureReferenceDigestMethods(digests); signingConfiguration.setSignatureCanonicalizationAlgorithm(canonicalization); signingConfiguration.setKeyInfoGeneratorManager(buildSignatureKeyInfoGeneratorManager()); criteria.add(new SignatureSigningConfigurationCriterion(signingConfiguration)); try { SignatureSigningParameters parameters = resolver.resolveSingle(criteria); Assert.notNull(parameters, "Failed to resolve any signing credential"); return parameters; } catch (Exception ex) { throw new Saml2Exception(ex); } } private static NamedKeyInfoGeneratorManager buildSignatureKeyInfoGeneratorManager() { final NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); namedManager.setUseDefaultManager(true); final KeyInfoGeneratorManager defaultManager = namedManager.getDefaultManager(); // Generator for X509Credentials final X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); x509Factory.setEmitEntityCertificate(true); x509Factory.setEmitEntityCertificateChain(true); defaultManager.registerFactory(x509Factory); return namedManager; } private static List<Credential> resolveSigningCredentials(RelyingPartyRegistration relyingPartyRegistration) { List<Credential> credentials = new ArrayList<>(); for (Saml2X509Credential x509Credential : relyingPartyRegistration.getSigningX509Credentials()) { X509Certificate certificate = x509Credential.getCertificate(); PrivateKey privateKey = x509Credential.getPrivateKey(); BasicCredential credential = CredentialSupport.getSimpleCredential(certificate, privateKey); credential.setEntityId(relyingPartyRegistration.getEntityId()); credential.setUsageType(UsageType.SIGNING); credentials.add(credential); } return credentials; } private OpenSamlSigningUtils() { } static class QueryParametersPartial { final RelyingPartyRegistration registration; final Map<String, String> components = new LinkedHashMap<>(); QueryParametersPartial(RelyingPartyRegistration registration) { this.registration = registration; } QueryParametersPartial param(String key, String value) { this.components.put(key, value); return this; } Map<String, String> parameters() { SignatureSigningParameters parameters = resolveSigningParameters(this.registration); Credential credential = parameters.getSigningCredential(); String algorithmUri = parameters.getSignatureAlgorithm(); this.components.put(Saml2ParameterNames.SIG_ALG, algorithmUri); UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); for (Map.Entry<String, String> component : this.components.entrySet()) { builder.queryParam(component.getKey(), UriUtils.encode(component.getValue(), StandardCharsets.ISO_8859_1)); } String queryString = builder.build(true).toString().substring(1); try { byte[] rawSignature = XMLSigningUtil.signWithURI(credential, algorithmUri, queryString.getBytes(StandardCharsets.UTF_8)); String b64Signature = Saml2Utils.samlEncode(rawSignature); this.components.put(Saml2ParameterNames.SIGNATURE, b64Signature); } catch (SecurityException ex) { throw new Saml2Exception(ex); } return this.components; } } }
7,947
39.758974
111
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutResponseResolver.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.function.BiConsumer; import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.xml.ParserPool; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.core.xml.io.MarshallingException; 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.Status; import org.opensaml.saml.saml2.core.StatusCode; import org.opensaml.saml.saml2.core.impl.IssuerBuilder; import org.opensaml.saml.saml2.core.impl.LogoutRequestUnmarshaller; import org.opensaml.saml.saml2.core.impl.LogoutResponseBuilder; import org.opensaml.saml.saml2.core.impl.LogoutResponseMarshaller; import org.opensaml.saml.saml2.core.impl.StatusBuilder; import org.opensaml.saml.saml2.core.impl.StatusCodeBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSamlSigningUtils.QueryParametersPartial; import org.springframework.util.Assert; /** * For internal use only. Intended for consolidating common behavior related to minting a * SAML 2.0 Logout Response. */ final class OpenSamlLogoutResponseResolver { static { OpenSamlInitializationService.initialize(); } private final Log logger = LogFactory.getLog(getClass()); private final ParserPool parserPool; private final LogoutRequestUnmarshaller unmarshaller; private final LogoutResponseMarshaller marshaller; private final LogoutResponseBuilder logoutResponseBuilder; private final IssuerBuilder issuerBuilder; private final StatusBuilder statusBuilder; private final StatusCodeBuilder statusCodeBuilder; private final RelyingPartyRegistrationRepository registrations; private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; /** * Construct a {@link OpenSamlLogoutResponseResolver} */ OpenSamlLogoutResponseResolver(RelyingPartyRegistrationRepository registrations, RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { this.registrations = registrations; this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = registry.getParserPool(); this.unmarshaller = (LogoutRequestUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() .getUnmarshaller(LogoutRequest.DEFAULT_ELEMENT_NAME); this.marshaller = (LogoutResponseMarshaller) registry.getMarshallerFactory() .getMarshaller(LogoutResponse.DEFAULT_ELEMENT_NAME); Assert.notNull(this.marshaller, "logoutResponseMarshaller must be configured in OpenSAML"); this.logoutResponseBuilder = (LogoutResponseBuilder) registry.getBuilderFactory() .getBuilder(LogoutResponse.DEFAULT_ELEMENT_NAME); Assert.notNull(this.logoutResponseBuilder, "logoutResponseBuilder must be configured in OpenSAML"); this.issuerBuilder = (IssuerBuilder) registry.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME); Assert.notNull(this.issuerBuilder, "issuerBuilder must be configured in OpenSAML"); this.statusBuilder = (StatusBuilder) registry.getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME); Assert.notNull(this.statusBuilder, "statusBuilder must be configured in OpenSAML"); this.statusCodeBuilder = (StatusCodeBuilder) registry.getBuilderFactory() .getBuilder(StatusCode.DEFAULT_ELEMENT_NAME); Assert.notNull(this.statusCodeBuilder, "statusCodeBuilder must be configured in OpenSAML"); } /** * Prepare to create, sign, and serialize a SAML 2.0 Logout Response. * * By default, includes a {@code RelayState} based on the {@link HttpServletRequest} * as well as the {@code Destination} and {@code Issuer} based on the * {@link RelyingPartyRegistration} derived from the {@link Authentication}. The * logout response is also marked as {@code SUCCESS}. * @param request the HTTP request * @param authentication the current user * @return a signed and serialized SAML 2.0 Logout Response */ Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication) { return resolve(request, authentication, (registration, logoutResponse) -> { }); } Saml2LogoutResponse resolve(HttpServletRequest request, Authentication authentication, BiConsumer<RelyingPartyRegistration, LogoutResponse> logoutResponseConsumer) { LogoutRequest logoutRequest = parse(extractSamlRequest(request)); String registrationId = getRegistrationId(authentication); RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, registrationId); if (registration == null && this.registrations != null) { String issuer = logoutRequest.getIssuer().getValue(); registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer); } if (registration == null) { return null; } if (registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation() == null) { return null; } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); LogoutResponse logoutResponse = this.logoutResponseBuilder.buildObject(); logoutResponse.setDestination(registration.getAssertingPartyDetails().getSingleLogoutServiceResponseLocation()); Issuer issuer = this.issuerBuilder.buildObject(); issuer.setValue(entityId); logoutResponse.setIssuer(issuer); StatusCode code = this.statusCodeBuilder.buildObject(); code.setValue(StatusCode.SUCCESS); Status status = this.statusBuilder.buildObject(); status.setStatusCode(code); logoutResponse.setStatus(status); logoutResponse.setInResponseTo(logoutRequest.getID()); if (logoutResponse.getID() == null) { logoutResponse.setID("LR" + UUID.randomUUID()); } logoutResponseConsumer.accept(registration, logoutResponse); Saml2LogoutResponse.Builder result = Saml2LogoutResponse.withRelyingPartyRegistration(registration); if (registration.getAssertingPartyDetails().getSingleLogoutServiceBinding() == Saml2MessageBinding.POST) { String xml = serialize(OpenSamlSigningUtils.sign(logoutResponse, registration)); String samlResponse = Saml2Utils.samlEncode(xml.getBytes(StandardCharsets.UTF_8)); result.samlResponse(samlResponse); if (request.getParameter(Saml2ParameterNames.RELAY_STATE) != null) { result.relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)); } return result.build(); } else { String xml = serialize(logoutResponse); String deflatedAndEncoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(xml)); result.samlResponse(deflatedAndEncoded); QueryParametersPartial partial = OpenSamlSigningUtils.sign(registration) .param(Saml2ParameterNames.SAML_RESPONSE, deflatedAndEncoded); if (request.getParameter(Saml2ParameterNames.RELAY_STATE) != null) { partial.param(Saml2ParameterNames.RELAY_STATE, request.getParameter(Saml2ParameterNames.RELAY_STATE)); } return result.parameters((params) -> params.putAll(partial.parameters())).build(); } } private String getRegistrationId(Authentication authentication) { if (this.logger.isTraceEnabled()) { this.logger.trace("Attempting to resolve registrationId from " + authentication); } if (authentication == null) { return null; } Object principal = authentication.getPrincipal(); if (principal instanceof Saml2AuthenticatedPrincipal) { return ((Saml2AuthenticatedPrincipal) principal).getRelyingPartyRegistrationId(); } return null; } private String extractSamlRequest(HttpServletRequest request) { String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); byte[] b = Saml2Utils.samlDecode(serialized); if (Saml2MessageBindingUtils.isHttpRedirectBinding(request)) { return Saml2Utils.samlInflate(b); } return new String(b, StandardCharsets.UTF_8); } private LogoutRequest parse(String request) throws Saml2Exception { try { Document document = this.parserPool .parse(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutRequest) this.unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception("Failed to deserialize LogoutRequest", ex); } } private String serialize(LogoutResponse logoutResponse) { try { Element element = this.marshaller.marshall(logoutResponse); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } }
10,905
45.408511
129
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestResolver.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.nio.charset.StandardCharsets; import java.util.UUID; import java.util.function.BiConsumer; import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.xml.SerializeSupport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.io.MarshallingException; 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.SessionIndex; import org.opensaml.saml.saml2.core.impl.IssuerBuilder; import org.opensaml.saml.saml2.core.impl.LogoutRequestBuilder; import org.opensaml.saml.saml2.core.impl.LogoutRequestMarshaller; import org.opensaml.saml.saml2.core.impl.NameIDBuilder; import org.opensaml.saml.saml2.core.impl.SessionIndexBuilder; import org.w3c.dom.Element; import org.springframework.core.convert.converter.Converter; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.saml2.provider.service.web.authentication.logout.OpenSamlSigningUtils.QueryParametersPartial; import org.springframework.util.Assert; /** * For internal use only. Intended for consolidating common behavior related to minting a * SAML 2.0 Logout Request. */ final class OpenSamlLogoutRequestResolver { static { OpenSamlInitializationService.initialize(); } private final Log logger = LogFactory.getLog(getClass()); private final LogoutRequestMarshaller marshaller; private final IssuerBuilder issuerBuilder; private final NameIDBuilder nameIdBuilder; private final SessionIndexBuilder sessionIndexBuilder; private final LogoutRequestBuilder logoutRequestBuilder; private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; private Converter<HttpServletRequest, String> relayStateResolver = (request) -> UUID.randomUUID().toString(); /** * Construct a {@link OpenSamlLogoutRequestResolver} */ OpenSamlLogoutRequestResolver(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver) { this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.marshaller = (LogoutRequestMarshaller) registry.getMarshallerFactory() .getMarshaller(LogoutRequest.DEFAULT_ELEMENT_NAME); Assert.notNull(this.marshaller, "logoutRequestMarshaller must be configured in OpenSAML"); this.logoutRequestBuilder = (LogoutRequestBuilder) registry.getBuilderFactory() .getBuilder(LogoutRequest.DEFAULT_ELEMENT_NAME); Assert.notNull(this.logoutRequestBuilder, "logoutRequestBuilder must be configured in OpenSAML"); this.issuerBuilder = (IssuerBuilder) registry.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME); Assert.notNull(this.issuerBuilder, "issuerBuilder must be configured in OpenSAML"); this.nameIdBuilder = (NameIDBuilder) registry.getBuilderFactory().getBuilder(NameID.DEFAULT_ELEMENT_NAME); Assert.notNull(this.nameIdBuilder, "nameIdBuilder must be configured in OpenSAML"); this.sessionIndexBuilder = (SessionIndexBuilder) registry.getBuilderFactory() .getBuilder(SessionIndex.DEFAULT_ELEMENT_NAME); Assert.notNull(this.sessionIndexBuilder, "sessionIndexBuilder must be configured in OpenSAML"); } void setRelayStateResolver(Converter<HttpServletRequest, String> relayStateResolver) { this.relayStateResolver = relayStateResolver; } /** * Prepare to create, sign, and serialize a SAML 2.0 Logout Request. * * By default, includes a {@code NameID} based on the {@link Authentication} instance * as well as the {@code Destination} and {@code Issuer} based on the * {@link RelyingPartyRegistration} derived from the {@link Authentication}. * @param request the HTTP request * @param authentication the current user * @return a signed and serialized SAML 2.0 Logout Request */ Saml2LogoutRequest resolve(HttpServletRequest request, Authentication authentication) { return resolve(request, authentication, (registration, logoutRequest) -> { }); } Saml2LogoutRequest resolve(HttpServletRequest request, Authentication authentication, BiConsumer<RelyingPartyRegistration, LogoutRequest> logoutRequestConsumer) { String registrationId = getRegistrationId(authentication); RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, registrationId); if (registration == null) { return null; } if (registration.getAssertingPartyDetails().getSingleLogoutServiceLocation() == null) { return null; } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); LogoutRequest logoutRequest = this.logoutRequestBuilder.buildObject(); logoutRequest.setDestination(registration.getAssertingPartyDetails().getSingleLogoutServiceLocation()); Issuer issuer = this.issuerBuilder.buildObject(); issuer.setValue(entityId); logoutRequest.setIssuer(issuer); NameID nameId = this.nameIdBuilder.buildObject(); nameId.setValue(authentication.getName()); logoutRequest.setNameID(nameId); if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal) { Saml2AuthenticatedPrincipal principal = (Saml2AuthenticatedPrincipal) authentication.getPrincipal(); for (String index : principal.getSessionIndexes()) { SessionIndex sessionIndex = this.sessionIndexBuilder.buildObject(); sessionIndex.setValue(index); logoutRequest.getSessionIndexes().add(sessionIndex); } } logoutRequestConsumer.accept(registration, logoutRequest); if (logoutRequest.getID() == null) { logoutRequest.setID("LR" + UUID.randomUUID()); } String relayState = this.relayStateResolver.convert(request); Saml2LogoutRequest.Builder result = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .id(logoutRequest.getID()); if (registration.getAssertingPartyDetails().getSingleLogoutServiceBinding() == Saml2MessageBinding.POST) { String xml = serialize(OpenSamlSigningUtils.sign(logoutRequest, registration)); String samlRequest = Saml2Utils.samlEncode(xml.getBytes(StandardCharsets.UTF_8)); return result.samlRequest(samlRequest).relayState(relayState).build(); } else { String xml = serialize(logoutRequest); String deflatedAndEncoded = Saml2Utils.samlEncode(Saml2Utils.samlDeflate(xml)); result.samlRequest(deflatedAndEncoded); QueryParametersPartial partial = OpenSamlSigningUtils.sign(registration) .param(Saml2ParameterNames.SAML_REQUEST, deflatedAndEncoded) .param(Saml2ParameterNames.RELAY_STATE, relayState); return result.parameters((params) -> params.putAll(partial.parameters())).build(); } } private String getRegistrationId(Authentication authentication) { if (this.logger.isTraceEnabled()) { this.logger.trace("Attempting to resolve registrationId from " + authentication); } if (authentication == null) { return null; } Object principal = authentication.getPrincipal(); if (principal instanceof Saml2AuthenticatedPrincipal) { return ((Saml2AuthenticatedPrincipal) principal).getRelyingPartyRegistrationId(); } return null; } private String serialize(LogoutRequest logoutRequest) { try { Element element = this.marshaller.marshall(logoutRequest); return SerializeSupport.nodeToString(element); } catch (MarshallingException ex) { throw new Saml2Exception(ex); } } }
9,282
45.883838
129
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/OpenSamlLogoutRequestValidatorParametersResolver.java
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; import jakarta.servlet.http.HttpServletRequest; import net.shibboleth.utilities.java.support.xml.ParserPool; import org.opensaml.core.config.ConfigurationService; import org.opensaml.core.xml.config.XMLObjectProviderRegistry; import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport; import org.opensaml.saml.saml2.core.LogoutRequest; import org.opensaml.saml.saml2.core.impl.LogoutRequestUnmarshaller; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.springframework.http.HttpMethod; import org.springframework.security.core.Authentication; import org.springframework.security.saml2.Saml2Exception; import org.springframework.security.saml2.core.OpenSamlInitializationService; import org.springframework.security.saml2.core.Saml2Error; import org.springframework.security.saml2.core.Saml2ErrorCodes; import org.springframework.security.saml2.core.Saml2ParameterNames; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticatedPrincipal; import org.springframework.security.saml2.provider.service.authentication.Saml2AuthenticationException; import org.springframework.security.saml2.provider.service.authentication.logout.OpenSamlLogoutRequestValidator; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutRequestValidatorParameters; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.OrRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; /** * An OpenSAML-based implementation of * {@link Saml2LogoutRequestValidatorParametersResolver} */ public final class OpenSamlLogoutRequestValidatorParametersResolver implements Saml2LogoutRequestValidatorParametersResolver { static { OpenSamlInitializationService.initialize(); } private RequestMatcher requestMatcher = new OrRequestMatcher( new AntPathRequestMatcher("/logout/saml2/slo/{registrationId}"), new AntPathRequestMatcher("/logout/saml2/slo")); private final RelyingPartyRegistrationRepository registrations; private final ParserPool parserPool; private final LogoutRequestUnmarshaller unmarshaller; /** * Constructs a {@link OpenSamlLogoutRequestValidator} */ public OpenSamlLogoutRequestValidatorParametersResolver(RelyingPartyRegistrationRepository registrations) { Assert.notNull(registrations, "relyingPartyRegistrationRepository cannot be null"); XMLObjectProviderRegistry registry = ConfigurationService.get(XMLObjectProviderRegistry.class); this.parserPool = registry.getParserPool(); this.unmarshaller = (LogoutRequestUnmarshaller) XMLObjectProviderRegistrySupport.getUnmarshallerFactory() .getUnmarshaller(LogoutRequest.DEFAULT_ELEMENT_NAME); this.registrations = registrations; } /** * Construct the parameters necessary for validating an asserting party's * {@code <saml2:LogoutRequest>} based on the given {@link HttpServletRequest} * * <p> * Uses the configured {@link RequestMatcher} to identify the processing request, * including looking for any indicated {@code registrationId}. * * <p> * If a {@code registrationId} is found in the request, it will attempt to use that, * erroring if no {@link RelyingPartyRegistration} is found. * * <p> * If no {@code registrationId} is found in the request, it will look for a currently * logged-in user and use the associated {@code registrationId}. * * <p> * In the event that neither the URL nor any logged in user could determine a * {@code registrationId}, this code then will try and derive a * {@link RelyingPartyRegistration} given the {@code <saml2:LogoutRequest>}'s * {@code Issuer} value. * @param request the HTTP request * @return a {@link Saml2LogoutRequestValidatorParameters} instance, or {@code null} * if one could not be resolved * @throws Saml2AuthenticationException if the {@link RequestMatcher} specifies a * non-existent {@code registrationId} */ @Override public Saml2LogoutRequestValidatorParameters resolve(HttpServletRequest request, Authentication authentication) { if (request.getParameter(Saml2ParameterNames.SAML_REQUEST) == null) { return null; } RequestMatcher.MatchResult result = this.requestMatcher.matcher(request); if (!result.isMatch()) { return null; } String registrationId = getRegistrationId(result, authentication); if (registrationId == null) { return logoutRequestByEntityId(request, authentication); } return logoutRequestById(request, authentication, registrationId); } /** * The request matcher to use to identify a request to process a * {@code <saml2:LogoutRequest>}. By default, checks for {@code /logout/saml2/slo} and * {@code /logout/saml2/slo/{registrationId}}. * * <p> * Generally speaking, the URL does not need to have a {@code registrationId} in it * since either it can be looked up from the active logged in user or it can be * derived through the {@code Issuer} in the {@code <saml2:LogoutRequest>}. * @param requestMatcher the {@link RequestMatcher} to use */ public void setRequestMatcher(RequestMatcher requestMatcher) { Assert.notNull(requestMatcher, "requestMatcher cannot be null"); this.requestMatcher = requestMatcher; } private String getRegistrationId(RequestMatcher.MatchResult result, Authentication authentication) { String registrationId = result.getVariables().get("registrationId"); if (registrationId != null) { return registrationId; } if (authentication == null) { return null; } if (authentication.getPrincipal() instanceof Saml2AuthenticatedPrincipal principal) { return principal.getRelyingPartyRegistrationId(); } return null; } private Saml2LogoutRequestValidatorParameters logoutRequestById(HttpServletRequest request, Authentication authentication, String registrationId) { RelyingPartyRegistration registration = this.registrations.findByRegistrationId(registrationId); if (registration == null) { throw new Saml2AuthenticationException( new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "registration not found"), "registration not found"); } return logoutRequestByRegistration(request, registration, authentication); } private Saml2LogoutRequestValidatorParameters logoutRequestByEntityId(HttpServletRequest request, Authentication authentication) { String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); byte[] b = Saml2Utils.samlDecode(serialized); LogoutRequest logoutRequest = parse(inflateIfRequired(request, b)); String issuer = logoutRequest.getIssuer().getValue(); RelyingPartyRegistration registration = this.registrations.findUniqueByAssertingPartyEntityId(issuer); return logoutRequestByRegistration(request, registration, authentication); } private Saml2LogoutRequestValidatorParameters logoutRequestByRegistration(HttpServletRequest request, RelyingPartyRegistration registration, Authentication authentication) { if (registration == null) { return null; } Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); registration = fromRequest(request, registration); String serialized = request.getParameter(Saml2ParameterNames.SAML_REQUEST); Saml2LogoutRequest logoutRequest = Saml2LogoutRequest.withRelyingPartyRegistration(registration) .samlRequest(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)) .binding(saml2MessageBinding).location(registration.getSingleLogoutServiceLocation()) .parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, request.getParameter(Saml2ParameterNames.SIG_ALG))) .parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, request.getParameter(Saml2ParameterNames.SIGNATURE))) .parametersQuery((params) -> request.getQueryString()).build(); return new Saml2LogoutRequestValidatorParameters(logoutRequest, registration, authentication); } private String inflateIfRequired(HttpServletRequest request, byte[] b) { if (HttpMethod.GET.equals(request.getMethod())) { return Saml2Utils.samlInflate(b); } return new String(b, StandardCharsets.UTF_8); } private LogoutRequest parse(String request) throws Saml2Exception { try { Document document = this.parserPool .parse(new ByteArrayInputStream(request.getBytes(StandardCharsets.UTF_8))); Element element = document.getDocumentElement(); return (LogoutRequest) this.unmarshaller.unmarshall(element); } catch (Exception ex) { throw new Saml2Exception("Failed to deserialize LogoutRequest", ex); } } private RelyingPartyRegistration fromRequest(HttpServletRequest request, RelyingPartyRegistration registration) { RelyingPartyRegistrationPlaceholderResolvers.UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers .uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); return registration.mutate().entityId(entityId).singleLogoutServiceLocation(logoutLocation) .singleLogoutServiceResponseLocation(logoutResponseLocation).build(); } }
10,710
45.772926
119
java
null
spring-security-main/saml2/saml2-service-provider/src/main/java/org/springframework/security/saml2/provider/service/web/authentication/logout/Saml2LogoutResponseFilter.java
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.saml2.provider.service.web.authentication.logout; import java.io.IOException; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.log.LogMessage; 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.logout.Saml2LogoutRequest; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponse; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidator; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutResponseValidatorParameters; import org.springframework.security.saml2.provider.service.authentication.logout.Saml2LogoutValidatorResult; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration; import org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository; import org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationPlaceholderResolvers.UriResolver; import org.springframework.security.saml2.provider.service.web.RelyingPartyRegistrationResolver; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.util.Assert; import org.springframework.web.filter.OncePerRequestFilter; /** * A filter for handling a &lt;saml2:LogoutResponse&gt; sent from the asserting party. A * &lt;saml2:LogoutResponse&gt; is sent in response to a &lt;saml2:LogoutRequest&gt; * already sent by the relying party. * * Note that before a &lt;saml2:LogoutRequest&gt; is sent, the user is logged out. Given * that, this implementation should not use any {@link LogoutSuccessHandler} that relies * on the user being logged in. * * @author Josh Cummings * @since 5.6 * @see Saml2LogoutRequestRepository * @see Saml2LogoutResponseValidator */ public final class Saml2LogoutResponseFilter extends OncePerRequestFilter { private final Log logger = LogFactory.getLog(getClass()); private final RelyingPartyRegistrationResolver relyingPartyRegistrationResolver; private final Saml2LogoutResponseValidator logoutResponseValidator; private final LogoutSuccessHandler logoutSuccessHandler; private Saml2LogoutRequestRepository logoutRequestRepository = new HttpSessionLogoutRequestRepository(); private RequestMatcher logoutRequestMatcher = new AntPathRequestMatcher("/logout/saml2/slo"); public Saml2LogoutResponseFilter(RelyingPartyRegistrationRepository registrations, Saml2LogoutResponseValidator logoutResponseValidator, LogoutSuccessHandler logoutSuccessHandler) { this.relyingPartyRegistrationResolver = (request, id) -> { if (id == null) { return null; } return registrations.findByRegistrationId(id); }; this.logoutResponseValidator = logoutResponseValidator; this.logoutSuccessHandler = logoutSuccessHandler; } /** * Constructs a {@link Saml2LogoutResponseFilter} for accepting SAML 2.0 Logout * Responses from the asserting party * @param relyingPartyRegistrationResolver the strategy for resolving a * {@link RelyingPartyRegistration} * @param logoutResponseValidator authenticates the SAML 2.0 Logout Response * @param logoutSuccessHandler the action to perform now that logout has succeeded */ public Saml2LogoutResponseFilter(RelyingPartyRegistrationResolver relyingPartyRegistrationResolver, Saml2LogoutResponseValidator logoutResponseValidator, LogoutSuccessHandler logoutSuccessHandler) { this.relyingPartyRegistrationResolver = relyingPartyRegistrationResolver; this.logoutResponseValidator = logoutResponseValidator; this.logoutSuccessHandler = logoutSuccessHandler; } /** * {@inheritDoc} */ @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { if (!this.logoutRequestMatcher.matches(request)) { chain.doFilter(request, response); return; } if (request.getParameter(Saml2ParameterNames.SAML_RESPONSE) == null) { chain.doFilter(request, response); return; } Saml2LogoutRequest logoutRequest = this.logoutRequestRepository.removeLogoutRequest(request, response); if (logoutRequest == null) { this.logger.trace("Did not process logout response since could not find associated LogoutRequest"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Failed to find associated LogoutRequest"); return; } RelyingPartyRegistration registration = this.relyingPartyRegistrationResolver.resolve(request, logoutRequest.getRelyingPartyRegistrationId()); if (registration == null) { this.logger .trace("Did not process logout response since failed to find associated RelyingPartyRegistration"); Saml2Error error = new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, "Failed to find associated RelyingPartyRegistration"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, error.toString()); return; } if (registration.getSingleLogoutServiceResponseLocation() == null) { this.logger.trace( "Did not process logout response since RelyingPartyRegistration has not been configured with a logout response endpoint"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } UriResolver uriResolver = RelyingPartyRegistrationPlaceholderResolvers.uriResolver(request, registration); String entityId = uriResolver.resolve(registration.getEntityId()); String logoutLocation = uriResolver.resolve(registration.getSingleLogoutServiceLocation()); String logoutResponseLocation = uriResolver.resolve(registration.getSingleLogoutServiceResponseLocation()); registration = registration.mutate().entityId(entityId).singleLogoutServiceLocation(logoutLocation) .singleLogoutServiceResponseLocation(logoutResponseLocation).build(); Saml2MessageBinding saml2MessageBinding = Saml2MessageBindingUtils.resolveBinding(request); if (!registration.getSingleLogoutServiceBindings().contains(saml2MessageBinding)) { this.logger.trace("Did not process logout response since used incorrect binding"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } String serialized = request.getParameter(Saml2ParameterNames.SAML_RESPONSE); Saml2LogoutResponse logoutResponse = Saml2LogoutResponse.withRelyingPartyRegistration(registration) .samlResponse(serialized).relayState(request.getParameter(Saml2ParameterNames.RELAY_STATE)) .binding(saml2MessageBinding).location(registration.getSingleLogoutServiceResponseLocation()) .parameters((params) -> params.put(Saml2ParameterNames.SIG_ALG, request.getParameter(Saml2ParameterNames.SIG_ALG))) .parameters((params) -> params.put(Saml2ParameterNames.SIGNATURE, request.getParameter(Saml2ParameterNames.SIGNATURE))) .parametersQuery((params) -> request.getQueryString()).build(); Saml2LogoutResponseValidatorParameters parameters = new Saml2LogoutResponseValidatorParameters(logoutResponse, logoutRequest, registration); Saml2LogoutValidatorResult result = this.logoutResponseValidator.validate(parameters); if (result.hasErrors()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, result.getErrors().iterator().next().toString()); this.logger.debug(LogMessage.format("Failed to validate LogoutResponse: %s", result.getErrors())); return; } this.logoutSuccessHandler.onLogoutSuccess(request, response, null); } public void setLogoutRequestMatcher(RequestMatcher logoutRequestMatcher) { Assert.notNull(logoutRequestMatcher, "logoutRequestMatcher cannot be null"); this.logoutRequestMatcher = logoutRequestMatcher; } /** * Use this {@link Saml2LogoutRequestRepository} for retrieving the SAML 2.0 Logout * Request associated with the request's {@code RelayState} * @param logoutRequestRepository the {@link Saml2LogoutRequestRepository} to use */ public void setLogoutRequestRepository(Saml2LogoutRequestRepository logoutRequestRepository) { Assert.notNull(logoutRequestRepository, "logoutRequestRepository cannot be null"); this.logoutRequestRepository = logoutRequestRepository; } }
9,573
48.864583
127
java