Search in sources :

Example 56 with AuthnRequest

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

the class AbstractSamlIdPProfileHandlerController method singleSignOnSessionExists.

/**
 * Single sign on session exists.
 *
 * @param pair     the pair
 * @param request  the request
 * @param response the response
 * @return the boolean
 */
protected Optional<TicketGrantingTicket> singleSignOnSessionExists(final Pair<? extends SignableSAMLObject, MessageContext> pair, final HttpServletRequest request, final HttpServletResponse response) {
    val authnRequest = AuthnRequest.class.cast(pair.getLeft());
    if (authnRequest.isForceAuthn()) {
        LOGGER.trace("Authentication request asks for forced authn. Ignoring existing single sign-on session, if any");
        return Optional.empty();
    }
    val cookie = configurationContext.getTicketGrantingTicketCookieGenerator().retrieveCookieValue(request);
    if (StringUtils.isBlank(cookie)) {
        LOGGER.trace("Single sign-on session cannot be found or determined. Ignoring single sign-on session");
        return Optional.empty();
    }
    val ticketGrantingTicket = configurationContext.getTicketRegistrySupport().getTicketGrantingTicket(cookie);
    if (ticketGrantingTicket == null) {
        LOGGER.debug("Authentication transaction linked to single sign-on session cannot determined.");
        return Optional.empty();
    }
    val authn = ticketGrantingTicket.getAuthentication();
    LOGGER.debug("Located single sign-on authentication for principal [{}]", authn.getPrincipal());
    val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
    val service = configurationContext.getWebApplicationServiceFactory().createService(issuer);
    val registeredService = configurationContext.getServicesManager().findServiceBy(service);
    val ssoRequest = SingleSignOnParticipationRequest.builder().httpServletRequest(request).build().attribute(Service.class.getName(), service).attribute(RegisteredService.class.getName(), registeredService).attribute(Issuer.class.getName(), issuer).attribute(Authentication.class.getName(), authn).attribute(TicketGrantingTicket.class.getName(), cookie).attribute(AuthnRequest.class.getName(), authnRequest);
    val ssoStrategy = configurationContext.getSingleSignOnParticipationStrategy();
    LOGGER.debug("Checking for single sign-on participation for issuer [{}]", issuer);
    val ssoAvailable = ssoStrategy.supports(ssoRequest) && ssoStrategy.isParticipating(ssoRequest);
    return ssoAvailable ? Optional.of(ticketGrantingTicket) : Optional.empty();
}
Also used : lombok.val(lombok.val) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) RegisteredService(org.apereo.cas.services.RegisteredService) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Authentication(org.apereo.cas.authentication.Authentication)

Example 57 with AuthnRequest

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

the class AbstractSamlIdPProfileHandlerController method buildResponseBasedSingleSignOnSession.

/**
 * Build response based single sign on session.
 * The http response before encoding the SAML response is reset
 * to ensure a clean slate from previous attempts, specially
 * when requests/responses are produced rapidly.
 *
 * @param context              the pair
 * @param ticketGrantingTicket the authentication
 * @param request              the request
 * @param response             the response
 * @throws Exception the exception
 */
protected void buildResponseBasedSingleSignOnSession(final Pair<? extends RequestAbstractType, MessageContext> context, final TicketGrantingTicket ticketGrantingTicket, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    val authnRequest = (AuthnRequest) context.getLeft();
    val id = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
    val service = configurationContext.getWebApplicationServiceFactory().createService(id);
    service.getAttributes().put(SamlProtocolConstants.PARAMETER_ENTITY_ID, CollectionUtils.wrapList(id));
    val registeredService = configurationContext.getServicesManager().findServiceBy(service, SamlRegisteredService.class);
    val audit = AuditableContext.builder().service(service).authentication(ticketGrantingTicket.getAuthentication()).registeredService(registeredService).httpRequest(request).httpResponse(response).build();
    val accessResult = configurationContext.getRegisteredServiceAccessStrategyEnforcer().execute(audit);
    accessResult.throwExceptionIfNeeded();
    val assertion = buildCasAssertion(ticketGrantingTicket.getAuthentication(), service, registeredService, Map.of());
    val authenticationContext = buildAuthenticationContextPair(request, response, context);
    val binding = determineProfileBinding(authenticationContext);
    val messageContext = authenticationContext.getRight();
    val relayState = SAMLBindingSupport.getRelayState(messageContext);
    SAMLBindingSupport.setRelayState(authenticationContext.getRight(), relayState);
    response.reset();
    val factory = (ServiceTicketFactory) getConfigurationContext().getTicketFactory().get(ServiceTicket.class);
    val st = factory.create(ticketGrantingTicket, service, false, ServiceTicket.class);
    getConfigurationContext().getTicketRegistry().addTicket(st);
    getConfigurationContext().getTicketRegistry().updateTicket(ticketGrantingTicket);
    buildSamlResponse(response, request, authenticationContext, assertion, binding);
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) ServiceTicketFactory(org.apereo.cas.ticket.ServiceTicketFactory) ServiceTicket(org.apereo.cas.ticket.ServiceTicket)

Example 58 with AuthnRequest

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

the class AbstractSamlIdPProfileHandlerController method verifySamlAuthenticationRequest.

/**
 * Verify saml authentication request.
 *
 * @param authenticationContext the pair
 * @param request               the request
 * @return the pair
 * @throws Exception the exception
 */
protected Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> verifySamlAuthenticationRequest(final Pair<? extends RequestAbstractType, MessageContext> authenticationContext, final HttpServletRequest request) throws Exception {
    val authnRequest = (AuthnRequest) authenticationContext.getKey();
    val issuer = SamlIdPUtils.getIssuerFromSamlObject(authnRequest);
    LOGGER.debug("Located issuer [{}] from authentication request", issuer);
    val registeredService = verifySamlRegisteredService(issuer);
    LOGGER.debug("Fetching SAML2 metadata adaptor for [{}]", issuer);
    val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(configurationContext.getSamlRegisteredServiceCachingMetadataResolver(), registeredService, authnRequest);
    if (adaptor.isEmpty()) {
        LOGGER.warn("No metadata could be found for [{}]", issuer);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
    }
    val facade = adaptor.get();
    verifyAuthenticationContextSignature(authenticationContext, request, authnRequest, facade, registeredService);
    val binding = determineProfileBinding(authenticationContext);
    val acs = SamlIdPUtils.determineEndpointForRequest(Pair.of(authnRequest, authenticationContext.getRight()), facade, binding);
    LOGGER.debug("Determined SAML2 endpoint for authentication request as [{}]", StringUtils.defaultIfBlank(acs.getResponseLocation(), acs.getLocation()));
    SamlUtils.logSamlObject(configurationContext.getOpenSamlConfigBean(), authnRequest);
    return Pair.of(registeredService, facade);
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 59 with AuthnRequest

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

use of org.opensaml.saml.saml2.core.AuthnRequest in project ddf by codice.

the class IdpHandler method doHttpRedirectBinding.

private void doHttpRedirectBinding(HttpServletRequest request, HttpServletResponse response) throws AuthenticationFailureException {
    String redirectUrl;
    String idpRequest = null;
    String relayState = createRelayState(request);
    try {
        IDPSSODescriptor idpssoDescriptor = idpMetadata.getDescriptor();
        if (idpssoDescriptor == null) {
            throw new AuthenticationFailureException(IDP_METADATA_MISSING);
        }
        StringBuilder queryParams = new StringBuilder("SAMLRequest=").append(encodeAuthnRequest(createAndSignAuthnRequest(false, idpssoDescriptor.getWantAuthnRequestsSigned()), false));
        if (relayState != null) {
            queryParams.append("&RelayState=").append(URLEncoder.encode(relayState, "UTF-8"));
        }
        idpRequest = idpMetadata.getSingleSignOnLocation() + "?" + queryParams;
        UriBuilder idpUri = new UriBuilderImpl(new URI(idpRequest));
        simpleSign.signUriString(queryParams.toString(), idpUri);
        redirectUrl = idpUri.build().toString();
    } catch (UnsupportedEncodingException e) {
        LOGGER.info("Unable to encode relay state: {}", relayState, e);
        throw new AuthenticationFailureException("Unable to create return location");
    } catch (SignatureException e) {
        String msg = "Unable to sign request";
        LOGGER.info(msg, e);
        throw new AuthenticationFailureException(msg);
    } catch (URISyntaxException e) {
        LOGGER.info("Unable to parse IDP request location: {}", idpRequest, e);
        throw new AuthenticationFailureException("Unable to determine IDP location.");
    }
    try {
        response.sendRedirect(redirectUrl);
        response.flushBuffer();
    } catch (IOException e) {
        LOGGER.info("Unable to redirect AuthnRequest to {}", redirectUrl, e);
        throw new AuthenticationFailureException("Unable to redirect to IdP");
    }
}
Also used : IDPSSODescriptor(org.opensaml.saml.saml2.metadata.IDPSSODescriptor) UnsupportedEncodingException(java.io.UnsupportedEncodingException) AuthenticationFailureException(org.codice.ddf.platform.filter.AuthenticationFailureException) SignatureException(ddf.security.samlp.SignatureException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UriBuilder(javax.ws.rs.core.UriBuilder) UriBuilderImpl(org.apache.cxf.jaxrs.impl.UriBuilderImpl) URI(java.net.URI)

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