Search in sources :

Example 31 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project cas by apereo.

the class SamlIdPDelegatedClientAuthenticationRequestCustomizer method customize.

@Override
public void customize(final IndirectClient client, final WebContext webContext) {
    val authnRequestResult = SamlIdPUtils.retrieveSamlRequest(webContext, sessionStore, openSamlConfigBean, AuthnRequest.class).map(Pair::getLeft).map(AuthnRequest.class::cast);
    authnRequestResult.ifPresent(authnRequest -> {
        LOGGER.debug("Retrieved the SAML2 authentication request from [{}]", SamlIdPUtils.getIssuerFromSamlObject(authnRequest));
        if (authnRequest.isForceAuthn()) {
            webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_FORCE_AUTHN, true);
        }
        if (authnRequest.isPassive()) {
            webContext.setRequestAttribute(RedirectionActionBuilder.ATTRIBUTE_PASSIVE, true);
        }
        val requestedAuthnContext = authnRequest.getRequestedAuthnContext();
        if (requestedAuthnContext != null && requestedAuthnContext.getAuthnContextClassRefs() != null && !requestedAuthnContext.getAuthnContextClassRefs().isEmpty()) {
            val refs = requestedAuthnContext.getAuthnContextClassRefs().stream().map(XSURI::getURI).collect(Collectors.toList());
            webContext.setRequestAttribute(SAML2ConfigurationContext.REQUEST_ATTR_AUTHN_CONTEXT_CLASS_REFS, refs);
            webContext.setRequestAttribute(SAML2ConfigurationContext.REQUEST_ATTR_COMPARISON_TYPE, requestedAuthnContext.getComparison().name());
        }
    });
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest)

Example 32 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project cas by apereo.

the class BaseSamlRegisteredServiceAttributeReleasePolicy method getSamlAuthnRequest.

/**
 * Gets saml authn request.
 *
 * @param applicationContext the application context
 * @return the saml authn request
 */
protected static Optional<AuthnRequest> getSamlAuthnRequest(final ApplicationContext applicationContext) {
    val openSamlConfigBean = applicationContext.getBean(OpenSamlConfigBean.DEFAULT_BEAN_NAME, OpenSamlConfigBean.class);
    val sessionStore = applicationContext.getBean(DistributedJEESessionStore.DEFAULT_BEAN_NAME, SessionStore.class);
    val request = HttpRequestUtils.getHttpServletRequestFromRequestAttributes();
    val response = HttpRequestUtils.getHttpServletResponseFromRequestAttributes();
    val context = new JEEContext(request, response);
    val result = SamlIdPUtils.retrieveSamlRequest(context, sessionStore, openSamlConfigBean, AuthnRequest.class);
    val authnRequest = (AuthnRequest) result.orElseThrow(() -> new IllegalArgumentException("SAML request could not be determined from session store")).getLeft();
    return Optional.of(authnRequest);
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) JEEContext(org.pac4j.core.context.JEEContext)

Example 33 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project cas by apereo.

the class BaseSamlRegisteredServiceAttributeReleasePolicy method getEntityIdFromRequest.

/**
 * Gets entity id from request.
 *
 * @param selectedService the selected service
 * @return the entity id from request
 */
protected static String getEntityIdFromRequest(final Service selectedService) {
    val request = HttpRequestUtils.getHttpServletRequestFromRequestAttributes();
    if (request == null || selectedService == null) {
        LOGGER.debug("No http request could be identified to locate the entity id");
        return null;
    }
    LOGGER.debug("Attempting to determine entity id for service [{}]", selectedService);
    val entityIdAttribute = selectedService.getAttributes().get(SamlProtocolConstants.PARAMETER_ENTITY_ID);
    if (entityIdAttribute != null && !entityIdAttribute.isEmpty()) {
        LOGGER.debug("Found entity id [{}] as a service attribute", entityIdAttribute);
        return CollectionUtils.firstElement(entityIdAttribute).map(Object::toString).orElseThrow();
    }
    val providerIdAttribute = selectedService.getAttributes().get(SamlIdPConstants.PROVIDER_ID);
    if (providerIdAttribute != null && !providerIdAttribute.isEmpty()) {
        LOGGER.debug("Found provider entity id [{}] as a service attribute", providerIdAttribute);
        return CollectionUtils.firstElement(providerIdAttribute).map(Object::toString).orElseThrow();
    }
    val samlRequest = selectedService.getAttributes().get(SamlProtocolConstants.PARAMETER_SAML_REQUEST);
    if (samlRequest != null && !samlRequest.isEmpty()) {
        val applicationContext = ApplicationContextProvider.getApplicationContext();
        val resolver = applicationContext.getBean(SamlRegisteredServiceCachingMetadataResolver.DEFAULT_BEAN_NAME, SamlRegisteredServiceCachingMetadataResolver.class);
        val attributeValue = CollectionUtils.firstElement(samlRequest).map(Object::toString).orElseThrow();
        val openSamlConfigBean = resolver.getOpenSamlConfigBean();
        val authnRequest = SamlIdPUtils.retrieveSamlRequest(openSamlConfigBean, RequestAbstractType.class, attributeValue);
        SamlUtils.logSamlObject(openSamlConfigBean, authnRequest);
        val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
        LOGGER.debug("Found entity id [{}] from SAML request issuer", issuer);
        return issuer;
    }
    val entityId = request.getParameter(SamlProtocolConstants.PARAMETER_ENTITY_ID);
    if (StringUtils.isNotBlank(entityId)) {
        LOGGER.debug("Found entity id [{}] as a request parameter", entityId);
        return entityId;
    }
    val svcParam = request.getParameter(CasProtocolConstants.PARAMETER_SERVICE);
    return FunctionUtils.doIf(StringUtils.isNotBlank(svcParam), () -> FunctionUtils.doAndHandle(o -> {
        val builder = new URIBuilder(svcParam);
        return builder.getQueryParams().stream().filter(p -> p.getName().equals(SamlProtocolConstants.PARAMETER_ENTITY_ID)).map(NameValuePair::getValue).findFirst().orElse(StringUtils.EMPTY);
    }, throwable -> {
        LoggingUtils.error(LOGGER, throwable);
        return null;
    }).apply(svcParam), () -> null).get();
}
Also used : lombok.val(lombok.val) RegisteredServiceAttributeReleasePolicyContext(org.apereo.cas.services.RegisteredServiceAttributeReleasePolicyContext) DistributedJEESessionStore(org.apereo.cas.pac4j.DistributedJEESessionStore) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) SamlUtils(org.apereo.cas.support.saml.SamlUtils) LoggingUtils(org.apereo.cas.util.LoggingUtils) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) Map(java.util.Map) CollectionUtils(org.apereo.cas.util.CollectionUtils) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) ApplicationContextProvider(org.apereo.cas.util.spring.ApplicationContextProvider) JEEContext(org.pac4j.core.context.JEEContext) CasProtocolConstants(org.apereo.cas.CasProtocolConstants) URIBuilder(org.apache.http.client.utils.URIBuilder) lombok.val(lombok.val) RequestAbstractType(org.opensaml.saml.saml2.core.RequestAbstractType) SessionStore(org.pac4j.core.context.session.SessionStore) ApplicationContext(org.springframework.context.ApplicationContext) SamlIdPUtils(org.apereo.cas.support.saml.SamlIdPUtils) OpenSamlConfigBean(org.apereo.cas.support.saml.OpenSamlConfigBean) SamlProtocolConstants(org.apereo.cas.support.saml.SamlProtocolConstants) HttpRequestUtils(org.apereo.cas.util.HttpRequestUtils) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Service(org.apereo.cas.authentication.principal.Service) SamlIdPConstants(org.apereo.cas.support.saml.SamlIdPConstants) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Optional(java.util.Optional) ReturnAllowedAttributeReleasePolicy(org.apereo.cas.services.ReturnAllowedAttributeReleasePolicy) NameValuePair(org.apache.http.NameValuePair) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) URIBuilder(org.apache.http.client.utils.URIBuilder)

Example 34 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project cas by apereo.

the class SamlIdPUtils method retrieveSamlRequest.

/**
 * Retrieve authn request authn request.
 *
 * @param context            the context
 * @param sessionStore       the session store
 * @param openSamlConfigBean the open saml config bean
 * @param clazz              the clazz
 * @return the request
 */
public static Optional<Pair<? extends RequestAbstractType, MessageContext>> retrieveSamlRequest(final WebContext context, final SessionStore sessionStore, final OpenSamlConfigBean openSamlConfigBean, final Class<? extends RequestAbstractType> clazz) {
    LOGGER.trace("Retrieving authentication request from scope");
    val authnContext = sessionStore.get(context, SamlProtocolConstants.PARAMETER_SAML_REQUEST).map(String.class::cast).map(value -> retrieveSamlRequest(openSamlConfigBean, clazz, value)).flatMap(authnRequest -> sessionStore.get(context, MessageContext.class.getName()).map(String.class::cast).map(result -> SamlIdPAuthenticationContext.decode(result).toMessageContext(authnRequest)));
    return authnContext.map(ctx -> Pair.of((AuthnRequest) ctx.getMessage(), ctx));
}
Also used : lombok.val(lombok.val) MessageContext(org.opensaml.messaging.context.MessageContext) SneakyThrows(lombok.SneakyThrows) Inflater(java.util.zip.Inflater) SamlIdPAuthenticationContext(org.apereo.cas.support.saml.authentication.SamlIdPAuthenticationContext) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) StringUtils(org.apache.commons.lang3.StringUtils) LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) StatusResponseType(org.opensaml.saml.saml2.core.StatusResponseType) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) SAMLBindingSupport(org.opensaml.saml.common.binding.SAMLBindingSupport) Pair(org.apache.commons.lang3.tuple.Pair) ByteArrayInputStream(java.io.ByteArrayInputStream) AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) Unchecked(org.jooq.lambda.Unchecked) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) Base64Support(net.shibboleth.utilities.java.support.codec.Base64Support) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) RequestAbstractType(org.opensaml.saml.saml2.core.RequestAbstractType) SessionStore(org.pac4j.core.context.session.SessionStore) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) Slf4j(lombok.extern.slf4j.Slf4j) SAMLObject(org.opensaml.saml.common.SAMLObject) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) SAMLPeerEntityContext(org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext) Optional(java.util.Optional) EncodingUtils(org.apereo.cas.util.EncodingUtils) InflaterInputStream(java.util.zip.InflaterInputStream) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) XMLObjectSupport(org.opensaml.core.xml.util.XMLObjectSupport) UtilityClass(lombok.experimental.UtilityClass) WebContext(org.pac4j.core.context.WebContext) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) SamlIdPSamlRegisteredServiceCriterion(org.apereo.cas.support.saml.idp.metadata.locator.SamlIdPSamlRegisteredServiceCriterion) Assertion(org.opensaml.saml.saml2.core.Assertion) RoleDescriptorResolver(org.opensaml.saml.metadata.resolver.RoleDescriptorResolver) IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) JEEContext(org.pac4j.core.context.JEEContext) ServicesManager(org.apereo.cas.services.ServicesManager) lombok.val(lombok.val) PredicateRoleDescriptorResolver(org.opensaml.saml.metadata.resolver.impl.PredicateRoleDescriptorResolver) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) EvaluableEntityRoleEntityDescriptorCriterion(org.opensaml.saml.metadata.criteria.entity.impl.EvaluableEntityRoleEntityDescriptorCriterion) SAMLEndpointContext(org.opensaml.saml.common.messaging.context.SAMLEndpointContext) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest)

Example 35 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project cas by apereo.

the class SamlIdPUtils method getAssertionConsumerServiceFromRequest.

private static AssertionConsumerService getAssertionConsumerServiceFromRequest(final RequestAbstractType request, final String binding, final SamlRegisteredServiceServiceProviderMetadataFacade adapter) {
    if (request instanceof AuthnRequest) {
        val authnRequest = AuthnRequest.class.cast(request);
        var acsUrl = authnRequest.getAssertionConsumerServiceURL();
        val acsIndex = authnRequest.getAssertionConsumerServiceIndex();
        if (StringUtils.isBlank(acsUrl) && acsIndex == null) {
            LOGGER.debug("No assertion consumer service url or index is supplied in the authentication request");
            return null;
        }
        if (StringUtils.isBlank(acsUrl) && acsIndex != null) {
            LOGGER.debug("Locating assertion consumer service url for binding [{}] and index [{}]", acsUrl, acsIndex);
            acsUrl = adapter.getAssertionConsumerServiceFor(binding, acsIndex).orElseGet(() -> {
                LOGGER.warn("Unable to locate acs url in for entity [{}] and binding [{}] with index [{}]", adapter.getEntityId(), binding, acsIndex);
                return null;
            });
        }
        if (StringUtils.isNotBlank(acsUrl)) {
            LOGGER.debug("Fetched assertion consumer service url [{}] with binding [{}] from authentication request", acsUrl, binding);
            val builder = new AssertionConsumerServiceBuilder();
            val endpoint = builder.buildObject(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
            endpoint.setBinding(binding);
            endpoint.setResponseLocation(acsUrl);
            endpoint.setLocation(acsUrl);
            endpoint.setIndex(acsIndex);
            return endpoint;
        }
    }
    return null;
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)113 Test (org.junit.jupiter.api.Test)35 lombok.val (lombok.val)26 Issuer (org.opensaml.saml.saml2.core.Issuer)21 AuthnRequestBuilder.anAuthnRequest (uk.gov.ida.saml.core.test.builders.AuthnRequestBuilder.anAuthnRequest)15 IdaAuthnRequestFromHub (uk.gov.ida.saml.hub.domain.IdaAuthnRequestFromHub)12 IdaAuthnRequestBuilder.anIdaAuthnRequest (uk.gov.ida.saml.hub.test.builders.IdaAuthnRequestBuilder.anIdaAuthnRequest)12 SAMLObjectBuilder (org.opensaml.saml.common.SAMLObjectBuilder)11 DateTime (org.joda.time.DateTime)10 MessageContext (org.opensaml.messaging.context.MessageContext)9 NameIDPolicy (org.opensaml.saml.saml2.core.NameIDPolicy)9 RequestedAuthnContext (org.opensaml.saml.saml2.core.RequestedAuthnContext)9 Document (org.w3c.dom.Document)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)8 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)8 XMLObject (org.opensaml.core.xml.XMLObject)7 IOException (java.io.IOException)6 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)6 AuthnRequestBuilder (org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder)6 IssuerBuilder (org.opensaml.saml.saml2.core.impl.IssuerBuilder)6