Search in sources :

Example 46 with AuthnRequest

use of org.opensaml.saml.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 47 with AuthnRequest

use of org.opensaml.saml.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 48 with AuthnRequest

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

the class AuthnRequestRequestedAttributesAttributeReleasePolicy method getAttributesForSamlRegisteredService.

@Override
protected Map<String, List<Object>> getAttributesForSamlRegisteredService(final Map<String, List<Object>> attributes, final ApplicationContext applicationContext, final SamlRegisteredServiceCachingMetadataResolver resolver, final SamlRegisteredServiceServiceProviderMetadataFacade facade, final EntityDescriptor entityDescriptor, final RegisteredServiceAttributeReleasePolicyContext context) {
    val releaseAttributes = new HashMap<String, List<Object>>();
    getSamlAuthnRequest(applicationContext).ifPresent(authnRequest -> {
        if (authnRequest.getExtensions() != null) {
            authnRequest.getExtensions().getUnknownXMLObjects().stream().filter(object -> object instanceof RequestedAttribute).map(object -> (RequestedAttribute) object).filter(attr -> {
                val name = this.useFriendlyName ? attr.getFriendlyName() : attr.getName();
                LOGGER.debug("Checking for requested attribute [{}] in metadata for [{}]", name, context.getRegisteredService().getName());
                return attributes.containsKey(name);
            }).forEach(attr -> {
                val name = this.useFriendlyName ? attr.getFriendlyName() : attr.getName();
                LOGGER.debug("Found requested attribute [{}] in metadata for [{}]", name, context.getRegisteredService().getName());
                releaseAttributes.put(name, attributes.get(name));
            });
        }
    });
    return authorizeReleaseOfAllowedAttributes(context, releaseAttributes);
}
Also used : lombok.val(lombok.val) Setter(lombok.Setter) RegisteredServiceAttributeReleasePolicyContext(org.apereo.cas.services.RegisteredServiceAttributeReleasePolicyContext) Getter(lombok.Getter) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) lombok.val(lombok.val) HashMap(java.util.HashMap) EqualsAndHashCode(lombok.EqualsAndHashCode) ApplicationContext(org.springframework.context.ApplicationContext) ArrayList(java.util.ArrayList) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Map(java.util.Map) ToString(lombok.ToString) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) AllArgsConstructor(lombok.AllArgsConstructor) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) ApplicationContextProvider(org.apereo.cas.util.spring.ApplicationContextProvider) RequestedAttribute(org.opensaml.saml.saml2.metadata.RequestedAttribute) NoArgsConstructor(lombok.NoArgsConstructor) HashMap(java.util.HashMap) RequestedAttribute(org.opensaml.saml.saml2.metadata.RequestedAttribute)

Example 49 with AuthnRequest

use of org.opensaml.saml.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)

Example 50 with AuthnRequest

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

the class SamlIdPMultifactorAuthenticationTriggerTests method verifyContextMapping.

@Test
public void verifyContextMapping() throws Exception {
    val registeredService = SamlIdPTestUtils.getSamlRegisteredService();
    val service = RegisteredServiceTestUtils.getService(registeredService.getServiceId());
    val authnRequest = SamlIdPTestUtils.getAuthnRequest(openSamlConfigBean, registeredService);
    var builder = (SAMLObjectBuilder) openSamlConfigBean.getBuilderFactory().getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    val classRef = (AuthnContextClassRef) builder.buildObject(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
    classRef.setURI("context1");
    builder = (SAMLObjectBuilder) openSamlConfigBean.getBuilderFactory().getBuilder(RequestedAuthnContext.DEFAULT_ELEMENT_NAME);
    val reqCtx = (RequestedAuthnContext) builder.buildObject(RequestedAuthnContext.DEFAULT_ELEMENT_NAME);
    reqCtx.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    reqCtx.getAuthnContextClassRefs().add(classRef);
    authnRequest.setRequestedAuthnContext(reqCtx);
    val request = new MockHttpServletRequest();
    val response = new MockHttpServletResponse();
    val messageContext = new MessageContext();
    messageContext.setMessage(authnRequest);
    val context = Pair.of(authnRequest, messageContext);
    SamlIdPUtils.storeSamlRequest(new JEEContext(request, response), openSamlConfigBean, samlIdPDistributedSessionStore, context);
    assertTrue(samlIdPMultifactorAuthenticationTrigger.supports(request, registeredService, RegisteredServiceTestUtils.getAuthentication(), service));
    val result = samlIdPMultifactorAuthenticationTrigger.isActivated(RegisteredServiceTestUtils.getAuthentication(), registeredService, request, response, service);
    assertTrue(result.isPresent());
}
Also used : lombok.val(lombok.val) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) JEEContext(org.pac4j.core.context.JEEContext) MessageContext(org.opensaml.messaging.context.MessageContext) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)113 Test (org.junit.jupiter.api.Test)42 lombok.val (lombok.val)40 Issuer (org.opensaml.saml.saml2.core.Issuer)28 AuthnRequestBuilder.anAuthnRequest (uk.gov.ida.saml.core.test.builders.AuthnRequestBuilder.anAuthnRequest)15 SAMLObjectBuilder (org.opensaml.saml.common.SAMLObjectBuilder)14 RequestedAuthnContext (org.opensaml.saml.saml2.core.RequestedAuthnContext)14 MessageContext (org.opensaml.messaging.context.MessageContext)13 IdaAuthnRequestFromHub (uk.gov.ida.saml.hub.domain.IdaAuthnRequestFromHub)12 IdaAuthnRequestBuilder.anIdaAuthnRequest (uk.gov.ida.saml.hub.test.builders.IdaAuthnRequestBuilder.anIdaAuthnRequest)12 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)11 DateTime (org.joda.time.DateTime)11 AuthnContextClassRef (org.opensaml.saml.saml2.core.AuthnContextClassRef)11 NameIDPolicy (org.opensaml.saml.saml2.core.NameIDPolicy)11 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)10 AssertionConsumerService (org.opensaml.saml.saml2.metadata.AssertionConsumerService)10 IOException (java.io.IOException)9 XMLObject (org.opensaml.core.xml.XMLObject)9 NameID (org.opensaml.saml.saml2.core.NameID)8 JEEContext (org.pac4j.core.context.JEEContext)8