Search in sources :

Example 1 with SingleSignOnService

use of org.opensaml.saml.saml2.metadata.SingleSignOnService in project verify-hub by alphagov.

the class CountrySingleSignOnServiceHelper method getSingleSignOn.

public URI getSingleSignOn(String entityId) {
    EidasMetadataResolver metadataResolver = new EidasMetadataResolver(new Timer(), client, URI.create(entityId));
    try {
        EntityDescriptor idpEntityDescriptor;
        try {
            CriteriaSet criteria = new CriteriaSet(new EntityIdCriterion(entityId));
            idpEntityDescriptor = metadataResolver.resolveSingle(criteria);
        } catch (ResolverException e) {
            LOG.error(format("Exception when accessing metadata: {0}", e));
            throw propagate(e);
        }
        if (idpEntityDescriptor != null) {
            final IDPSSODescriptor idpssoDescriptor = idpEntityDescriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
            final List<SingleSignOnService> singleSignOnServices = idpssoDescriptor.getSingleSignOnServices();
            if (singleSignOnServices.isEmpty()) {
                LOG.error(format("No singleSignOnServices present for IDP entityId: {0}", entityId));
            } else {
                if (singleSignOnServices.size() > 1) {
                    LOG.warn(format("More than one singleSignOnService present: {0} for {1}", singleSignOnServices.size(), entityId));
                }
                return URI.create(singleSignOnServices.get(0).getLocation());
            }
        }
        throw ApplicationException.createUnauditedException(ExceptionType.NOT_FOUND, UUID.randomUUID(), new RuntimeException(format("no entity descriptor for IDP: {0}", entityId)));
    } finally {
        if (metadataResolver != null) {
            metadataResolver.destroy();
        }
    }
}
Also used : EidasMetadataResolver(uk.gov.ida.hub.samlengine.EidasMetadataResolver) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ResolverException(net.shibboleth.utilities.java.support.resolver.ResolverException) Timer(java.util.Timer) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService)

Example 2 with SingleSignOnService

use of org.opensaml.saml.saml2.metadata.SingleSignOnService in project syncope by apache.

the class SAML2SPLogic method createLoginRequest.

@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2RequestTO createLoginRequest(final String spEntityID, final String idpEntityID) {
    check();
    // 1. look for IdP
    SAML2IdPEntity idp = StringUtils.isBlank(idpEntityID) ? cache.getFirst() : cache.get(idpEntityID);
    if (idp == null) {
        if (StringUtils.isBlank(idpEntityID)) {
            List<SAML2IdP> all = saml2IdPDAO.findAll();
            if (!all.isEmpty()) {
                idp = getIdP(all.get(0).getKey());
            }
        } else {
            idp = getIdP(idpEntityID);
        }
    }
    if (idp == null) {
        throw new NotFoundException(StringUtils.isBlank(idpEntityID) ? "Any SAML 2.0 IdP" : "SAML 2.0 IdP '" + idpEntityID + "'");
    }
    if (idp.getSSOLocation(idp.getBindingType()) == null) {
        throw new IllegalArgumentException("No SingleSignOnService available for " + idp.getId());
    }
    // 2. create AuthnRequest
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spEntityID);
    NameIDPolicy nameIDPolicy = new NameIDPolicyBuilder().buildObject();
    if (idp.supportsNameIDFormat(NameIDType.TRANSIENT)) {
        nameIDPolicy.setFormat(NameIDType.TRANSIENT);
    } else if (idp.supportsNameIDFormat(NameIDType.PERSISTENT)) {
        nameIDPolicy.setFormat(NameIDType.PERSISTENT);
    } else {
        throw new IllegalArgumentException("Could not find supported NameIDFormat for IdP " + idpEntityID);
    }
    nameIDPolicy.setAllowCreate(true);
    nameIDPolicy.setSPNameQualifier(spEntityID);
    AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
    RequestedAuthnContext requestedAuthnContext = new RequestedAuthnContextBuilder().buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID("_" + UUID_GENERATOR.generate().toString());
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setProtocolBinding(idp.getBindingType().getUri());
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(issuer);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);
    authnRequest.setDestination(idp.getSSOLocation(idp.getBindingType()).getLocation());
    SAML2RequestTO requestTO = new SAML2RequestTO();
    requestTO.setIdpServiceAddress(authnRequest.getDestination());
    requestTO.setBindingType(idp.getBindingType());
    try {
        // 3. generate relay state as JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_CLAIM_IDP_DEFLATE, idp.isUseDeflateEncoding());
        Triple<String, String, Date> relayState = accessTokenDataBinder.generateJWT(authnRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
        // 4. sign and encode AuthnRequest
        switch(idp.getBindingType()) {
            case REDIRECT:
                requestTO.setRelayState(URLEncoder.encode(relayState.getMiddle(), StandardCharsets.UTF_8.name()));
                requestTO.setContent(URLEncoder.encode(saml2rw.encode(authnRequest, true), StandardCharsets.UTF_8.name()));
                requestTO.setSignAlg(URLEncoder.encode(saml2rw.getSigAlgo(), StandardCharsets.UTF_8.name()));
                requestTO.setSignature(URLEncoder.encode(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()), StandardCharsets.UTF_8.name()));
                break;
            case POST:
            default:
                requestTO.setRelayState(relayState.getMiddle());
                saml2rw.sign(authnRequest);
                requestTO.setContent(saml2rw.encode(authnRequest, idp.isUseDeflateEncoding()));
        }
    } catch (Exception e) {
        LOG.error("While generating AuthnRequest", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return requestTO;
}
Also used : SAML2RequestTO(org.apache.syncope.common.lib.to.SAML2RequestTO) Issuer(org.opensaml.saml.saml2.core.Issuer) HashMap(java.util.HashMap) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) XSString(org.opensaml.core.xml.schema.XSString) AuthnContextClassRefBuilder(org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder) DateTime(org.joda.time.DateTime) SAML2IdP(org.apache.syncope.core.persistence.api.entity.SAML2IdP) NameIDPolicyBuilder(org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Date(java.util.Date) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) RequestedAuthnContextBuilder(org.opensaml.saml.saml2.core.impl.RequestedAuthnContextBuilder) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) SAML2IdPEntity(org.apache.syncope.core.logic.saml2.SAML2IdPEntity) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) XMLObject(org.opensaml.core.xml.XMLObject) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 3 with SingleSignOnService

use of org.opensaml.saml.saml2.metadata.SingleSignOnService in project pac4j by pac4j.

the class SAML2AuthnRequestBuilder method build.

@Override
public AuthnRequest build(final SAML2MessageContext context) {
    final SingleSignOnService ssoService = context.getIDPSingleSignOnService(this.bindingType);
    final String idx = this.assertionConsumerServiceIndex > 0 ? String.valueOf(assertionConsumerServiceIndex) : null;
    final AssertionConsumerService assertionConsumerService = context.getSPAssertionConsumerService(idx);
    return buildAuthnRequest(context, assertionConsumerService, ssoService);
}
Also used : SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService)

Example 4 with SingleSignOnService

use of org.opensaml.saml.saml2.metadata.SingleSignOnService in project pac4j by pac4j.

the class SAML2WebSSOMessageSender method sendMessage.

@Override
public void sendMessage(final SAML2MessageContext context, final AuthnRequest authnRequest, final Object relayState) {
    final SPSSODescriptor spDescriptor = context.getSPSSODescriptor();
    final IDPSSODescriptor idpssoDescriptor = context.getIDPSSODescriptor();
    final SingleSignOnService ssoService = context.getIDPSingleSignOnService(destinationBindingType);
    final AssertionConsumerService acsService = context.getSPAssertionConsumerService();
    final MessageEncoder encoder = getMessageEncoder(context);
    final SAML2MessageContext outboundContext = new SAML2MessageContext(context);
    outboundContext.getProfileRequestContext().setProfileId(context.getProfileRequestContext().getProfileId());
    outboundContext.getProfileRequestContext().setInboundMessageContext(context.getProfileRequestContext().getInboundMessageContext());
    outboundContext.getProfileRequestContext().setOutboundMessageContext(context.getProfileRequestContext().getOutboundMessageContext());
    outboundContext.setMessage(authnRequest);
    outboundContext.getSAMLEndpointContext().setEndpoint(acsService);
    outboundContext.getSAMLPeerEndpointContext().setEndpoint(ssoService);
    outboundContext.getSAMLPeerEntityContext().setRole(context.getSAMLPeerEntityContext().getRole());
    outboundContext.getSAMLPeerEntityContext().setEntityId(context.getSAMLPeerEntityContext().getEntityId());
    outboundContext.getSAMLProtocolContext().setProtocol(context.getSAMLProtocolContext().getProtocol());
    outboundContext.getSecurityParametersContext().setSignatureSigningParameters(this.signatureSigningParametersProvider.build(spDescriptor));
    if (relayState != null) {
        outboundContext.getSAMLBindingContext().setRelayState(relayState.toString());
    }
    try {
        invokeOutboundMessageHandlers(spDescriptor, idpssoDescriptor, outboundContext);
        encoder.setMessageContext(outboundContext);
        encoder.initialize();
        encoder.prepareContext();
        encoder.encode();
        final SAMLMessageStorage messageStorage = context.getSAMLMessageStorage();
        if (messageStorage != null) {
            messageStorage.storeMessage(authnRequest.getID(), authnRequest);
        }
    } catch (final MessageEncodingException e) {
        throw new SAMLException("Error encoding saml message", e);
    } catch (final ComponentInitializationException e) {
        throw new SAMLException("Error initializing saml encoder", e);
    }
}
Also used : SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) SAML2MessageContext(org.pac4j.saml.context.SAML2MessageContext) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) ComponentInitializationException(net.shibboleth.utilities.java.support.component.ComponentInitializationException) SingleSignOnService(org.opensaml.saml.saml2.metadata.SingleSignOnService) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) MessageEncoder(org.opensaml.messaging.encoder.MessageEncoder) SAMLMessageStorage(org.pac4j.saml.storage.SAMLMessageStorage) MessageEncodingException(org.opensaml.messaging.encoder.MessageEncodingException) SAMLException(org.pac4j.saml.exceptions.SAMLException)

Example 5 with SingleSignOnService

use of org.opensaml.saml.saml2.metadata.SingleSignOnService in project cloudstack by apache.

the class SAML2AuthManagerImpl method addIdpToMap.

private void addIdpToMap(EntityDescriptor descriptor, Map<String, SAMLProviderMetadata> idpMap) {
    SAMLProviderMetadata idpMetadata = new SAMLProviderMetadata();
    idpMetadata.setEntityId(descriptor.getEntityID());
    s_logger.debug("Adding IdP to the list of discovered IdPs: " + descriptor.getEntityID());
    if (descriptor.getOrganization() != null) {
        if (descriptor.getOrganization().getDisplayNames() != null) {
            for (OrganizationDisplayName orgName : descriptor.getOrganization().getDisplayNames()) {
                if (orgName != null && orgName.getName() != null) {
                    idpMetadata.setOrganizationName(orgName.getName().getLocalString());
                    break;
                }
            }
        }
        if (idpMetadata.getOrganizationName() == null && descriptor.getOrganization().getOrganizationNames() != null) {
            for (OrganizationName orgName : descriptor.getOrganization().getOrganizationNames()) {
                if (orgName != null && orgName.getName() != null) {
                    idpMetadata.setOrganizationName(orgName.getName().getLocalString());
                    break;
                }
            }
        }
        if (descriptor.getOrganization().getURLs() != null) {
            for (OrganizationURL organizationURL : descriptor.getOrganization().getURLs()) {
                if (organizationURL != null && organizationURL.getURL() != null) {
                    idpMetadata.setOrganizationUrl(organizationURL.getURL().getLocalString());
                    break;
                }
            }
        }
    }
    if (descriptor.getContactPersons() != null) {
        for (ContactPerson person : descriptor.getContactPersons()) {
            if (person == null || (person.getGivenName() == null && person.getSurName() == null) || person.getEmailAddresses() == null) {
                continue;
            }
            if (person.getGivenName() != null) {
                idpMetadata.setContactPersonName(person.getGivenName().getName());
            } else if (person.getSurName() != null) {
                idpMetadata.setContactPersonName(person.getSurName().getName());
            }
            for (EmailAddress emailAddress : person.getEmailAddresses()) {
                if (emailAddress != null && emailAddress.getAddress() != null) {
                    idpMetadata.setContactPersonEmail(emailAddress.getAddress());
                }
            }
            if (idpMetadata.getContactPersonName() != null && idpMetadata.getContactPersonEmail() != null) {
                break;
            }
        }
    }
    IDPSSODescriptor idpDescriptor = descriptor.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);
    if (idpDescriptor != null) {
        if (idpDescriptor.getSingleSignOnServices() != null) {
            for (SingleSignOnService ssos : idpDescriptor.getSingleSignOnServices()) {
                if (ssos.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
                    idpMetadata.setSsoUrl(ssos.getLocation());
                }
            }
        }
        if (idpDescriptor.getSingleLogoutServices() != null) {
            for (SingleLogoutService slos : idpDescriptor.getSingleLogoutServices()) {
                if (slos.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) {
                    idpMetadata.setSloUrl(slos.getLocation());
                }
            }
        }
        X509Certificate unspecifiedKey = null;
        if (idpDescriptor.getKeyDescriptors() != null) {
            for (KeyDescriptor kd : idpDescriptor.getKeyDescriptors()) {
                if (kd.getUse() == UsageType.SIGNING) {
                    try {
                        idpMetadata.setSigningCertificate(KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0));
                    } catch (CertificateException ignored) {
                        s_logger.info("[ignored] encountered invalid certificate signing.", ignored);
                    }
                }
                if (kd.getUse() == UsageType.ENCRYPTION) {
                    try {
                        idpMetadata.setEncryptionCertificate(KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0));
                    } catch (CertificateException ignored) {
                        s_logger.info("[ignored] encountered invalid certificate encryption.", ignored);
                    }
                }
                if (kd.getUse() == UsageType.UNSPECIFIED) {
                    try {
                        unspecifiedKey = KeyInfoHelper.getCertificates(kd.getKeyInfo()).get(0);
                    } catch (CertificateException ignored) {
                        s_logger.info("[ignored] encountered invalid certificate.", ignored);
                    }
                }
            }
        }
        if (idpMetadata.getSigningCertificate() == null && unspecifiedKey != null) {
            idpMetadata.setSigningCertificate(unspecifiedKey);
        }
        if (idpMetadata.getEncryptionCertificate() == null && unspecifiedKey != null) {
            idpMetadata.setEncryptionCertificate(unspecifiedKey);
        }
        if (idpMap.containsKey(idpMetadata.getEntityId())) {
            s_logger.warn("Duplicate IdP metadata found with entity Id: " + idpMetadata.getEntityId());
        }
        idpMap.put(idpMetadata.getEntityId(), idpMetadata);
    }
}
Also used : OrganizationName(org.opensaml.saml2.metadata.OrganizationName) OrganizationDisplayName(org.opensaml.saml2.metadata.OrganizationDisplayName) IDPSSODescriptor(org.opensaml.saml2.metadata.IDPSSODescriptor) SingleLogoutService(org.opensaml.saml2.metadata.SingleLogoutService) KeyDescriptor(org.opensaml.saml2.metadata.KeyDescriptor) SingleSignOnService(org.opensaml.saml2.metadata.SingleSignOnService) CertificateException(java.security.cert.CertificateException) ContactPerson(org.opensaml.saml2.metadata.ContactPerson) EmailAddress(org.opensaml.saml2.metadata.EmailAddress) X509Certificate(java.security.cert.X509Certificate) OrganizationURL(org.opensaml.saml2.metadata.OrganizationURL)

Aggregations

SingleSignOnService (org.opensaml.saml.saml2.metadata.SingleSignOnService)9 EntityDescriptor (org.opensaml.saml.saml2.metadata.EntityDescriptor)7 IDPSSODescriptor (org.opensaml.saml.saml2.metadata.IDPSSODescriptor)7 CriteriaSet (net.shibboleth.utilities.java.support.resolver.CriteriaSet)3 EntityIdCriterion (org.opensaml.core.criterion.EntityIdCriterion)3 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)3 CertificateException (java.security.cert.CertificateException)2 X509Certificate (java.security.cert.X509Certificate)2 Arrays (java.util.Arrays)2 List (java.util.List)2 ResolverException (net.shibboleth.utilities.java.support.resolver.ResolverException)2 Test (org.junit.Test)2 XMLObject (org.opensaml.core.xml.XMLObject)2 AuthnContextClassRef (org.opensaml.saml.saml2.core.AuthnContextClassRef)2 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)2 KeyDescriptor (org.opensaml.saml.saml2.metadata.KeyDescriptor)2 SingleLogoutService (org.opensaml.saml.saml2.metadata.SingleLogoutService)2 LogoutWrapper (ddf.security.samlp.LogoutWrapper)1 PAOS_BINDING (ddf.security.samlp.impl.SamlProtocol.PAOS_BINDING)1 POST_BINDING (ddf.security.samlp.impl.SamlProtocol.POST_BINDING)1