Search in sources :

Example 26 with AuthnRequest

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

the class SamlIdPMultifactorAuthenticationTrigger method supports.

@Override
public boolean supports(final HttpServletRequest request, final RegisteredService registeredService, final Authentication authentication, final Service service) {
    if (!getAuthenticationContextMappings().isEmpty()) {
        val response = HttpRequestUtils.getHttpServletResponseFromRequestAttributes();
        val context = new JEEContext(request, response);
        val result = SamlIdPUtils.retrieveSamlRequest(context, distributedSessionStore, openSamlConfigBean, AuthnRequest.class);
        if (result.isPresent()) {
            val authnRequest = (AuthnRequest) result.get().getLeft();
            return authnRequest.getRequestedAuthnContext() != null && authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs() != null && !authnRequest.getRequestedAuthnContext().getAuthnContextClassRefs().isEmpty();
        }
    }
    return false;
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) JEEContext(org.pac4j.core.context.JEEContext)

Example 27 with AuthnRequest

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

the class AbstractSamlIdPProfileHandlerController method issueAuthenticationRequestRedirect.

/**
 * Redirect request for authentication.
 *
 * @param pair     the pair
 * @param request  the request
 * @param response the response
 * @return the model and view
 * @throws Exception the exception
 */
protected ModelAndView issueAuthenticationRequestRedirect(final Pair<? extends SignableSAMLObject, MessageContext> pair, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    val authnRequest = (AuthnRequest) pair.getLeft();
    val serviceUrl = constructServiceUrl(request, response, pair);
    LOGGER.debug("Created service url [{}]", DigestUtils.abbreviate(serviceUrl));
    val properties = configurationContext.getCasProperties();
    val urlToRedirectTo = CommonUtils.constructRedirectUrl(properties.getServer().getLoginUrl(), CasProtocolConstants.PARAMETER_SERVICE, serviceUrl, authnRequest.isForceAuthn(), authnRequest.isPassive());
    LOGGER.debug("Redirecting SAML authN request to [{}]", urlToRedirectTo);
    val type = properties.getAuthn().getSamlIdp().getCore().getSessionStorageType();
    if (type == SamlIdPCoreProperties.SessionStorageTypes.BROWSER_SESSION_STORAGE) {
        val context = new JEEContext(request, response);
        val sessionStorage = configurationContext.getSessionStore().getTrackableSession(context).map(BrowserSessionStorage.class::cast).orElseThrow(() -> new IllegalStateException("Unable to determine trackable session for storage"));
        sessionStorage.setDestinationUrl(urlToRedirectTo);
        return new ModelAndView(CasWebflowConstants.VIEW_ID_SESSION_STORAGE_WRITE, BrowserSessionStorage.KEY_SESSION_STORAGE, sessionStorage);
    }
    LOGGER.debug("Redirecting SAML authN request to [{}]", urlToRedirectTo);
    val mv = new ModelAndView(new RedirectView(urlToRedirectTo));
    mv.setStatus(HttpStatus.FOUND);
    return mv;
}
Also used : lombok.val(lombok.val) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) JEEContext(org.pac4j.core.context.JEEContext) ModelAndView(org.springframework.web.servlet.ModelAndView) RedirectView(org.springframework.web.servlet.view.RedirectView)

Example 28 with AuthnRequest

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

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

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

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