Search in sources :

Example 1 with Builder

use of org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder in project spring-boot by spring-projects.

the class Saml2RelyingPartyRegistrationConfiguration method asRegistration.

private RelyingPartyRegistration asRegistration(String id, Registration properties) {
    boolean usingMetadata = StringUtils.hasText(properties.getIdentityprovider().getMetadataUri());
    Builder builder = (usingMetadata) ? RelyingPartyRegistrations.fromMetadataLocation(properties.getIdentityprovider().getMetadataUri()).registrationId(id) : RelyingPartyRegistration.withRegistrationId(id);
    builder.assertionConsumerServiceLocation(properties.getAcs().getLocation());
    builder.assertionConsumerServiceBinding(properties.getAcs().getBinding());
    builder.assertingPartyDetails(mapIdentityProvider(properties, usingMetadata));
    builder.signingX509Credentials((credentials) -> properties.getSigning().getCredentials().stream().map(this::asSigningCredential).forEach(credentials::add));
    builder.decryptionX509Credentials((credentials) -> properties.getDecryption().getCredentials().stream().map(this::asDecryptionCredential).forEach(credentials::add));
    builder.assertingPartyDetails((details) -> details.verificationX509Credentials((credentials) -> properties.getIdentityprovider().getVerification().getCredentials().stream().map(this::asVerificationCredential).forEach(credentials::add)));
    builder.entityId(properties.getEntityId());
    RelyingPartyRegistration registration = builder.build();
    boolean signRequest = registration.getAssertingPartyDetails().getWantAuthnRequestsSigned();
    validateSigningCredentials(properties, signRequest);
    return registration;
}
Also used : X509Certificate(java.security.cert.X509Certificate) Decryption(org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyProperties.Decryption) CertificateFactory(java.security.cert.CertificateFactory) RelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrationRepository) RsaKeyConverters(org.springframework.security.converter.RsaKeyConverters) InMemoryRelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Map(java.util.Map) Signing(org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyProperties.Registration.Signing) AssertingPartyDetails(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.AssertingPartyDetails) Resource(org.springframework.core.io.Resource) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Registration(org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyProperties.Registration) PropertyMapper(org.springframework.boot.context.properties.PropertyMapper) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) Collectors(java.util.stream.Collectors) Saml2X509CredentialType(org.springframework.security.saml2.core.Saml2X509Credential.Saml2X509CredentialType) Consumer(java.util.function.Consumer) Configuration(org.springframework.context.annotation.Configuration) List(java.util.List) Builder(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder) Bean(org.springframework.context.annotation.Bean) Verification(org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyProperties.Identityprovider.Verification) Conditional(org.springframework.context.annotation.Conditional) RelyingPartyRegistrations(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistrations) InputStream(java.io.InputStream) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) Builder(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder)

Example 2 with Builder

use of org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder in project midpoint by Evolveum.

the class SamlModuleWebSecurityConfiguration method createRelyingPartyRegistration.

private static void createRelyingPartyRegistration(RelyingPartyRegistration.Builder registrationBuilder, SamlAdditionalConfiguration.Builder additionalConfigBuilder, Saml2ProviderAuthenticationModuleType providerType, String publicHttpUrlPattern, SamlModuleWebSecurityConfiguration configuration, Saml2KeyAuthenticationModuleType keysType, Saml2ServiceProviderAuthenticationModuleType serviceProviderType, ServletRequest request) {
    String linkText = providerType.getLinkText() == null ? providerType.getEntityId() : providerType.getLinkText();
    additionalConfigBuilder.nameOfUsernameAttribute(providerType.getNameOfUsernameAttribute()).linkText(linkText);
    String registrationId = StringUtils.isNotEmpty(serviceProviderType.getAliasForPath()) ? serviceProviderType.getAliasForPath() : (StringUtils.isNotEmpty(serviceProviderType.getAlias()) ? serviceProviderType.getAlias() : serviceProviderType.getEntityId());
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(StringUtils.isNotBlank(publicHttpUrlPattern) ? publicHttpUrlPattern : getBasePath((HttpServletRequest) request));
    UriComponentsBuilder ssoBuilder = builder.cloneBuilder();
    ssoBuilder.pathSegment(AuthUtil.stripSlashes(configuration.getPrefixOfModule()) + SSO_LOCATION_URL_SUFFIX);
    UriComponentsBuilder logoutBuilder = builder.cloneBuilder();
    logoutBuilder.pathSegment(AuthUtil.stripSlashes(configuration.getPrefixOfModule()) + LOGOUT_LOCATION_URL_SUFFIX);
    registrationBuilder.registrationId(registrationId).entityId(serviceProviderType.getEntityId()).assertionConsumerServiceLocation(ssoBuilder.build().toUriString()).singleLogoutServiceLocation(logoutBuilder.build().toUriString()).assertingPartyDetails(party -> {
        party.entityId(providerType.getEntityId());
        if (serviceProviderType.isSignRequests() != null) {
            party.wantAuthnRequestsSigned(Boolean.TRUE.equals(serviceProviderType.isSignRequests()));
        }
        if (providerType.getVerificationKeys() != null && !providerType.getVerificationKeys().isEmpty()) {
            party.verificationX509Credentials(c -> providerType.getVerificationKeys().forEach(verKey -> {
                byte[] certbytes = new byte[0];
                try {
                    certbytes = protector.decryptString(verKey).getBytes();
                } catch (EncryptionException e) {
                    LOGGER.error("Couldn't obtain clear string for provider verification key");
                }
                try {
                    X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certbytes));
                    c.add(new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION));
                } catch (CertificateException e) {
                    LOGGER.error("Couldn't obtain certificate from " + verKey);
                }
            }));
        }
    });
    Saml2X509Credential activeCredential = null;
    ModuleSaml2SimpleKeyType simpleKeyType = keysType.getActiveSimpleKey();
    if (simpleKeyType != null) {
        activeCredential = getSaml2Credential(simpleKeyType, true);
    }
    ModuleSaml2KeyStoreKeyType storeKeyType = keysType.getActiveKeyStoreKey();
    if (storeKeyType != null) {
        activeCredential = getSaml2Credential(storeKeyType, true);
    }
    List<Saml2X509Credential> credentials = new ArrayList<>();
    if (activeCredential != null) {
        credentials.add(activeCredential);
    }
    if (keysType.getStandBySimpleKey() != null && !keysType.getStandBySimpleKey().isEmpty()) {
        for (ModuleSaml2SimpleKeyType standByKey : keysType.getStandBySimpleKey()) {
            Saml2X509Credential credential = getSaml2Credential(standByKey, false);
            if (credential != null) {
                credentials.add(credential);
            }
        }
    }
    if (keysType.getStandByKeyStoreKey() != null && !keysType.getStandByKeyStoreKey().isEmpty()) {
        for (ModuleSaml2KeyStoreKeyType standByKey : keysType.getStandByKeyStoreKey()) {
            Saml2X509Credential credential = getSaml2Credential(standByKey, false);
            if (credential != null) {
                credentials.add(credential);
            }
        }
    }
    if (!credentials.isEmpty()) {
        registrationBuilder.decryptionX509Credentials(c -> credentials.forEach(cred -> {
            if (cred.getCredentialTypes().contains(Saml2X509Credential.Saml2X509CredentialType.DECRYPTION)) {
                c.add(cred);
            }
        }));
        registrationBuilder.signingX509Credentials(c -> credentials.forEach(cred -> {
            if (cred.getCredentialTypes().contains(Saml2X509Credential.Saml2X509CredentialType.SIGNING)) {
                c.add(cred);
            }
        }));
    }
}
Also used : X509Certificate(java.security.cert.X509Certificate) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) CertificateFactory(java.security.cert.CertificateFactory) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) InMemoryRelyingPartyRegistrationRepository(org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository) HashMap(java.util.HashMap) Trace(com.evolveum.midpoint.util.logging.Trace) StringUtils(org.apache.commons.lang3.StringUtils) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) ArrayList(java.util.ArrayList) AuthUtil(com.evolveum.midpoint.authentication.api.util.AuthUtil) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultResourceLoader(org.springframework.core.io.DefaultResourceLoader) Map(java.util.Map) PKCSException(org.bouncycastle.pkcs.PKCSException) java.security(java.security) ServletRequest(javax.servlet.ServletRequest) MidpointAssertingPartyMetadataConverter(com.evolveum.midpoint.authentication.impl.saml.MidpointAssertingPartyMetadataConverter) AuthSequenceUtil.getBasePath(com.evolveum.midpoint.authentication.impl.util.AuthSequenceUtil.getBasePath) ResourceLoader(org.springframework.core.io.ResourceLoader) Files(java.nio.file.Files) Saml2Exception(org.springframework.security.saml2.Saml2Exception) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) CertificateException(java.security.cert.CertificateException) List(java.util.List) Certificate(java.security.cert.Certificate) java.io(java.io) Paths(java.nio.file.Paths) Protector(com.evolveum.midpoint.prism.crypto.Protector) Base64Exception(org.apache.cxf.common.util.Base64Exception) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) EncryptionException(com.evolveum.midpoint.prism.crypto.EncryptionException) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509Certificate(java.security.cert.X509Certificate)

Example 3 with Builder

use of org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder in project midpoint by Evolveum.

the class MidpointAssertingPartyMetadataConverter method convert.

public RelyingPartyRegistration.Builder convert(InputStream inputStream, Saml2ProviderAuthenticationModuleType providerConfig) {
    EntityDescriptor descriptor = entityDescriptor(inputStream);
    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()) {
        defineKeys(keyDescriptor, verification, encryption);
    }
    if (verification.isEmpty()) {
        throw new Saml2Exception("Metadata response is missing verification certificates, necessary for verifying SAML assertions");
    }
    RelyingPartyRegistration.Builder builder = RelyingPartyRegistration.withRegistrationId(descriptor.getEntityID()).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())));
    }
    defineSingleSingOnService(idpssoDescriptor, providerConfig.getAuthenticationRequestBinding(), builder);
    defineSingleLogoutService(idpssoDescriptor, builder);
    return builder;
}
Also used : RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) X509Certificate(java.security.cert.X509Certificate) UsageType(org.opensaml.security.credential.UsageType) OpenSamlInitializationService(org.springframework.security.saml2.core.OpenSamlInitializationService) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) Saml2Exception(org.springframework.security.saml2.Saml2Exception) ConfigurationService(org.opensaml.core.config.ConfigurationService) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) CertificateException(java.security.cert.CertificateException) StringUtils(org.apache.commons.lang3.StringUtils) XMLObjectProviderRegistry(org.opensaml.core.xml.config.XMLObjectProviderRegistry) KeyInfoSupport(org.opensaml.xmlsec.keyinfo.KeyInfoSupport) RelyingPartyRegistration(org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration) ArrayList(java.util.ArrayList) Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) ParserPool(net.shibboleth.utilities.java.support.xml.ParserPool) List(java.util.List) org.opensaml.saml.saml2.metadata(org.opensaml.saml.saml2.metadata) SigningMethod(org.opensaml.saml.ext.saml2alg.SigningMethod) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) XMLObject(org.opensaml.core.xml.XMLObject) SAMLConstants(org.opensaml.saml.common.xml.SAMLConstants) Saml2ProviderAuthenticationModuleType(com.evolveum.midpoint.xml.ns._public.common.common_3.Saml2ProviderAuthenticationModuleType) InputStream(java.io.InputStream) Saml2X509Credential(org.springframework.security.saml2.core.Saml2X509Credential) ArrayList(java.util.ArrayList) Saml2Exception(org.springframework.security.saml2.Saml2Exception) SigningMethod(org.opensaml.saml.ext.saml2alg.SigningMethod)

Example 4 with Builder

use of org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder in project midpoint by Evolveum.

the class MidpointAssertingPartyMetadataConverter method defineSingleLogoutService.

private void defineSingleLogoutService(IDPSSODescriptor idpssoDescriptor, RelyingPartyRegistration.Builder builder) {
    Saml2MessageBinding authBinding = null;
    for (SingleLogoutService singleLogoutService : idpssoDescriptor.getSingleLogoutServices()) {
        if (singleLogoutService.getBinding().equals(Saml2MessageBinding.POST.getUrn())) {
            authBinding = Saml2MessageBinding.POST;
        } else if (singleLogoutService.getBinding().equals(Saml2MessageBinding.REDIRECT.getUrn())) {
            authBinding = Saml2MessageBinding.REDIRECT;
        } else {
            continue;
        }
        Saml2MessageBinding finalAuthBinding = authBinding;
        builder.assertingPartyDetails((party) -> party.singleLogoutServiceLocation(singleLogoutService.getLocation()).singleLogoutServiceBinding(finalAuthBinding));
        break;
    }
    if (authBinding == null) {
        throw new Saml2Exception("Metadata response is missing a SingleLogoutService, necessary for sending LogoutRequests");
    }
}
Also used : Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) Saml2Exception(org.springframework.security.saml2.Saml2Exception)

Example 5 with Builder

use of org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration.Builder in project midpoint by Evolveum.

the class MidpointAssertingPartyMetadataConverter method defineSingleSingOnService.

private void defineSingleSingOnService(IDPSSODescriptor idpssoDescriptor, String authenticationRequestBinding, RelyingPartyRegistration.Builder builder) {
    Saml2MessageBinding defaultBinding = Saml2MessageBinding.from(authenticationRequestBinding);
    if (defaultBinding == null && StringUtils.isNotEmpty(authenticationRequestBinding) && !defaultBinding.equals(Saml2MessageBinding.POST) && !defaultBinding.equals(Saml2MessageBinding.REDIRECT)) {
        throw new Saml2Exception("Default request binding '" + defaultBinding.getUrn() + "' isn't supported." + "Supported bindings are 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' and 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'.");
    }
    Saml2MessageBinding authBinding = null;
    for (SingleSignOnService singleSignOnService : idpssoDescriptor.getSingleSignOnServices()) {
        if (singleSignOnService.getBinding().equals(Saml2MessageBinding.POST.getUrn()) && allowBaseOnConsideringDefaultBinding(defaultBinding, Saml2MessageBinding.POST)) {
            authBinding = Saml2MessageBinding.POST;
        } else if (singleSignOnService.getBinding().equals(Saml2MessageBinding.REDIRECT.getUrn()) && allowBaseOnConsideringDefaultBinding(defaultBinding, Saml2MessageBinding.REDIRECT)) {
            authBinding = Saml2MessageBinding.REDIRECT;
        } else {
            continue;
        }
        Saml2MessageBinding finalAuthBinding = authBinding;
        builder.assertingPartyDetails((party) -> party.singleSignOnServiceLocation(singleSignOnService.getLocation()).singleSignOnServiceBinding(finalAuthBinding));
        break;
    }
    if (authBinding == null) {
        String message = "Supported SingleSignOnService is missing in metadata response, necessary for sending authentication request. ";
        if (defaultBinding != null) {
            message = "Default SingleSignOnService '" + defaultBinding.getUrn() + "' is missing in metadata response, necessary for sending authentication request. ";
        }
        message = message + "Supported bindings are 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST' and 'urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect'.";
        throw new Saml2Exception(message);
    }
}
Also used : Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) Saml2Exception(org.springframework.security.saml2.Saml2Exception)

Aggregations

Saml2Exception (org.springframework.security.saml2.Saml2Exception)4 RelyingPartyRegistration (org.springframework.security.saml2.provider.service.registration.RelyingPartyRegistration)4 X509Certificate (java.security.cert.X509Certificate)3 List (java.util.List)3 Saml2X509Credential (org.springframework.security.saml2.core.Saml2X509Credential)3 Saml2MessageBinding (org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding)3 InputStream (java.io.InputStream)2 CertificateException (java.security.cert.CertificateException)2 CertificateFactory (java.security.cert.CertificateFactory)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 StringUtils (org.apache.commons.lang3.StringUtils)2 InMemoryRelyingPartyRegistrationRepository (org.springframework.security.saml2.provider.service.registration.InMemoryRelyingPartyRegistrationRepository)2 AuthUtil (com.evolveum.midpoint.authentication.api.util.AuthUtil)1 MidpointAssertingPartyMetadataConverter (com.evolveum.midpoint.authentication.impl.saml.MidpointAssertingPartyMetadataConverter)1 AuthSequenceUtil.getBasePath (com.evolveum.midpoint.authentication.impl.util.AuthSequenceUtil.getBasePath)1 EncryptionException (com.evolveum.midpoint.prism.crypto.EncryptionException)1 Protector (com.evolveum.midpoint.prism.crypto.Protector)1 Trace (com.evolveum.midpoint.util.logging.Trace)1 TraceManager (com.evolveum.midpoint.util.logging.TraceManager)1