Search in sources :

Example 6 with AuthnRequest

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

the class SSOSamlProfileCallbackHandlerController method validateRequestAndBuildCasAssertion.

private Assertion validateRequestAndBuildCasAssertion(final HttpServletResponse response, final HttpServletRequest request, final Pair<AuthnRequest, MessageContext> pair) throws Exception {
    final AuthnRequest authnRequest = pair.getKey();
    final String ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
    this.ticketValidator.setRenew(authnRequest.isForceAuthn());
    final String serviceUrl = constructServiceUrl(request, response, pair);
    LOGGER.trace("Created service url for validation: [{}]", serviceUrl);
    final Assertion assertion = this.ticketValidator.validate(ticket, serviceUrl);
    logCasValidationAssertion(assertion);
    return assertion;
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Assertion(org.jasig.cas.client.validation.Assertion)

Example 7 with AuthnRequest

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

the class AbstractSamlProfileHandlerController method constructServiceUrl.

/**
 * Construct service url string.
 *
 * @param request  the request
 * @param response the response
 * @param pair     the pair
 * @return the string
 * @throws SamlException the saml exception
 */
@SneakyThrows
protected String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response, final Pair<? extends SignableSAMLObject, MessageContext> pair) throws SamlException {
    final AuthnRequest authnRequest = AuthnRequest.class.cast(pair.getLeft());
    final MessageContext messageContext = pair.getRight();
    try (StringWriter writer = SamlUtils.transformSamlObject(this.configBean, authnRequest)) {
        final URLBuilder builder = new URLBuilder(this.callbackService.getId());
        builder.getQueryParams().add(new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_ENTITY_ID, SamlIdPUtils.getIssuerFromSamlRequest(authnRequest)));
        final String samlRequest = EncodingUtils.encodeBase64(writer.toString().getBytes(StandardCharsets.UTF_8));
        builder.getQueryParams().add(new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_SAML_REQUEST, samlRequest));
        builder.getQueryParams().add(new net.shibboleth.utilities.java.support.collection.Pair<>(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, SAMLBindingSupport.getRelayState(messageContext)));
        final String url = builder.buildURL();
        LOGGER.trace("Built service callback url [{}]", url);
        return CommonUtils.constructServiceUrl(request, response, url, casProperties.getServer().getName(), CasProtocolConstants.PARAMETER_SERVICE, CasProtocolConstants.PARAMETER_TICKET, false);
    }
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) StringWriter(java.io.StringWriter) MessageContext(org.opensaml.messaging.context.MessageContext) URLBuilder(net.shibboleth.utilities.java.support.net.URLBuilder) SneakyThrows(lombok.SneakyThrows)

Example 8 with AuthnRequest

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

the class AbstractSamlProfileHandlerController method issueAuthenticationRequestRedirect.

/**
 * Redirect request for authentication.
 *
 * @param pair     the pair
 * @param request  the request
 * @param response the response
 * @throws Exception the exception
 */
protected void issueAuthenticationRequestRedirect(final Pair<? extends SignableSAMLObject, MessageContext> pair, final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    final AuthnRequest authnRequest = AuthnRequest.class.cast(pair.getLeft());
    final String serviceUrl = constructServiceUrl(request, response, pair);
    LOGGER.debug("Created service url [{}]", serviceUrl);
    final String initialUrl = CommonUtils.constructRedirectUrl(casProperties.getServer().getLoginUrl(), CasProtocolConstants.PARAMETER_SERVICE, serviceUrl, authnRequest.isForceAuthn(), authnRequest.isPassive());
    final String urlToRedirectTo = buildRedirectUrlByRequestedAuthnContext(initialUrl, authnRequest, request);
    LOGGER.debug("Redirecting SAML authN request to [{}]", urlToRedirectTo);
    final AuthenticationRedirectStrategy authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy();
    authenticationRedirectStrategy.redirect(request, response, urlToRedirectTo);
}
Also used : DefaultAuthenticationRedirectStrategy(org.jasig.cas.client.authentication.DefaultAuthenticationRedirectStrategy) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) DefaultAuthenticationRedirectStrategy(org.jasig.cas.client.authentication.DefaultAuthenticationRedirectStrategy) AuthenticationRedirectStrategy(org.jasig.cas.client.authentication.AuthenticationRedirectStrategy)

Example 9 with AuthnRequest

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

the class AbstractSamlProfileHandlerController method retrieveSamlAuthenticationRequestFromHttpRequest.

/**
 * Retrieve authn request authn request.
 *
 * @param request the request
 * @return the authn request
 * @throws Exception the exception
 */
protected AuthnRequest retrieveSamlAuthenticationRequestFromHttpRequest(final HttpServletRequest request) throws Exception {
    LOGGER.debug("Retrieving authentication request from scope");
    final String requestValue = request.getParameter(SamlProtocolConstants.PARAMETER_SAML_REQUEST);
    if (StringUtils.isBlank(requestValue)) {
        throw new IllegalArgumentException("SAML request could not be determined from the authentication request");
    }
    final byte[] encodedRequest = EncodingUtils.decodeBase64(requestValue.getBytes(StandardCharsets.UTF_8));
    final AuthnRequest authnRequest = (AuthnRequest) XMLObjectSupport.unmarshallFromInputStream(this.configBean.getParserPool(), new ByteArrayInputStream(encodedRequest));
    return authnRequest;
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 10 with AuthnRequest

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

the class IdPInitiatedProfileHandlerController method handleIdPInitiatedSsoRequest.

/**
 * Handle idp initiated sso requests.
 *
 * @param response the response
 * @param request  the request
 * @throws Exception the exception
 */
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_IDP_INIT_PROFILE_SSO)
protected void handleIdPInitiatedSsoRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    // The name (i.e., the entity ID) of the service provider.
    final String providerId = CommonUtils.safeGetParameter(request, SamlIdPConstants.PROVIDER_ID);
    if (StringUtils.isBlank(providerId)) {
        LOGGER.warn("No providerId parameter given in unsolicited SSO authentication request.");
        throw new MessageDecodingException("No providerId parameter given in unsolicited SSO authentication request.");
    }
    final SamlRegisteredService registeredService = verifySamlRegisteredService(providerId);
    final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = getSamlMetadataFacadeFor(registeredService, providerId);
    if (!adaptor.isPresent()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + providerId);
    }
    // The URL of the response location at the SP (called the "Assertion Consumer Service")
    // but can be omitted in favor of the IdP picking the default endpoint location from metadata.
    String shire = CommonUtils.safeGetParameter(request, SamlIdPConstants.SHIRE);
    final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Resolving service provider assertion consumer service URL for [{}] and binding [{}]", providerId, SAMLConstants.SAML2_POST_BINDING_URI);
        @NonNull final AssertionConsumerService acs = facade.getAssertionConsumerService(SAMLConstants.SAML2_POST_BINDING_URI);
        shire = acs.getLocation();
    }
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Unable to resolve service provider assertion consumer service URL for AuthnRequest construction for entityID: [{}]", providerId);
        throw new MessageDecodingException("Unable to resolve SP ACS URL for AuthnRequest construction");
    }
    // The target resource at the SP, or a state token generated by an SP to represent the resource.
    final String target = CommonUtils.safeGetParameter(request, SamlIdPConstants.TARGET);
    // A timestamp to help with stale request detection.
    final String time = CommonUtils.safeGetParameter(request, SamlIdPConstants.TIME);
    final SAMLObjectBuilder builder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(AuthnRequest.DEFAULT_ELEMENT_NAME);
    final AuthnRequest authnRequest = (AuthnRequest) builder.buildObject();
    authnRequest.setAssertionConsumerServiceURL(shire);
    final SAMLObjectBuilder isBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
    final Issuer issuer = (Issuer) isBuilder.buildObject();
    issuer.setValue(providerId);
    authnRequest.setIssuer(issuer);
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    final SAMLObjectBuilder pBuilder = (SAMLObjectBuilder) configBean.getBuilderFactory().getBuilder(NameIDPolicy.DEFAULT_ELEMENT_NAME);
    final NameIDPolicy nameIDPolicy = (NameIDPolicy) pBuilder.buildObject();
    nameIDPolicy.setAllowCreate(Boolean.TRUE);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    if (NumberUtils.isCreatable(time)) {
        authnRequest.setIssueInstant(new DateTime(TimeUnit.SECONDS.convert(Long.parseLong(time), TimeUnit.MILLISECONDS), ISOChronology.getInstanceUTC()));
    } else {
        authnRequest.setIssueInstant(new DateTime(DateTime.now(), ISOChronology.getInstanceUTC()));
    }
    authnRequest.setForceAuthn(Boolean.FALSE);
    if (StringUtils.isNotBlank(target)) {
        request.setAttribute(SamlProtocolConstants.PARAMETER_SAML_RELAY_STATE, target);
    }
    final MessageContext ctx = new MessageContext();
    ctx.setAutoCreateSubcontexts(true);
    if (facade.isAuthnRequestsSigned()) {
        samlObjectSigner.encode(authnRequest, registeredService, facade, response, request, SAMLConstants.SAML2_POST_BINDING_URI);
    }
    ctx.setMessage(authnRequest);
    ctx.getSubcontext(SAMLBindingContext.class, true).setHasBindingSignature(false);
    final Pair<SignableSAMLObject, MessageContext> pair = Pair.of(authnRequest, ctx);
    initiateAuthenticationRequest(pair, response, request);
}
Also used : SAMLBindingContext(org.opensaml.saml.common.messaging.context.SAMLBindingContext) SAMLObjectBuilder(org.opensaml.saml.common.SAMLObjectBuilder) Issuer(org.opensaml.saml.saml2.core.Issuer) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) DateTime(org.joda.time.DateTime) MessageDecodingException(org.opensaml.messaging.decoder.MessageDecodingException) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) NonNull(lombok.NonNull) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

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