Search in sources :

Example 6 with MessageContext

use of org.opensaml.messaging.context.MessageContext 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);
    if (StringUtils.isBlank(shire)) {
        shire = adaptor.get().getAssertionConsumerService().getLocation();
    }
    if (StringUtils.isBlank(shire)) {
        LOGGER.warn("Unable to resolve SP ACS 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 (adaptor.get().isAuthnRequestsSigned()) {
        samlObjectSigner.encode(authnRequest, registeredService, adaptor.get(), response, request);
    }
    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) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Example 7 with MessageContext

use of org.opensaml.messaging.context.MessageContext in project cas by apereo.

the class Saml10ObjectBuilder method encodeSamlResponse.

/**
     * Encode response and pass it onto the outbound transport.
     * Uses {@link CasHttpSoap11Encoder} to handle encoding.
     *
     * @param httpResponse the http response
     * @param httpRequest the http request
     * @param samlMessage the saml response
     * @throws Exception the exception in case encoding fails.
     */
public void encodeSamlResponse(final HttpServletResponse httpResponse, final HttpServletRequest httpRequest, final Response samlMessage) throws Exception {
    SamlUtils.logSamlObject(this.configBean, samlMessage);
    final HTTPSOAP11Encoder encoder = new CasHttpSoap11Encoder();
    final MessageContext<SAMLObject> context = new MessageContext();
    context.setMessage(samlMessage);
    encoder.setHttpServletResponse(httpResponse);
    encoder.setMessageContext(context);
    encoder.initialize();
    encoder.prepareContext();
    encoder.encode();
}
Also used : SAMLObject(org.opensaml.saml.common.SAMLObject) HTTPSOAP11Encoder(org.opensaml.saml.saml1.binding.encoding.impl.HTTPSOAP11Encoder) MessageContext(org.opensaml.messaging.context.MessageContext)

Example 8 with MessageContext

use of org.opensaml.messaging.context.MessageContext in project cas by apereo.

the class SamlProfileSaml2ResponseBuilder method encode.

@Override
protected Response encode(final SamlRegisteredService service, final Response samlResponse, final HttpServletResponse httpResponse, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String relayState) throws SamlException {
    try {
        final HTTPPostEncoder encoder = new HTTPPostEncoder();
        encoder.setHttpServletResponse(httpResponse);
        encoder.setVelocityEngine(this.velocityEngineFactory.createVelocityEngine());
        final MessageContext outboundMessageContext = new MessageContext<>();
        SamlIdPUtils.preparePeerEntitySamlEndpointContext(outboundMessageContext, adaptor);
        outboundMessageContext.setMessage(samlResponse);
        SAMLBindingSupport.setRelayState(outboundMessageContext, relayState);
        encoder.setMessageContext(outboundMessageContext);
        encoder.initialize();
        encoder.encode();
        return samlResponse;
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
Also used : HTTPPostEncoder(org.opensaml.saml.saml2.binding.encoding.impl.HTTPPostEncoder) MessageContext(org.opensaml.messaging.context.MessageContext) SamlException(org.apereo.cas.support.saml.SamlException)

Example 9 with MessageContext

use of org.opensaml.messaging.context.MessageContext in project cas by apereo.

the class AbstractSamlSLOProfileHandlerController method handleSloProfileRequest.

/**
     * Handle profile request.
     *
     * @param response the response
     * @param request  the request
     * @param decoder  the decoder
     * @throws Exception the exception
     */
protected void handleSloProfileRequest(final HttpServletResponse response, final HttpServletRequest request, final BaseHttpServletRequestXMLMessageDecoder decoder) throws Exception {
    if (singleLogoutCallbacksDisabled) {
        LOGGER.info("Processing SAML IdP SLO requests is disabled");
        return;
    }
    final Pair<? extends SignableSAMLObject, MessageContext> pair = decodeSamlContextFromHttpRequest(request, decoder, LogoutRequest.class);
    final LogoutRequest logoutRequest = LogoutRequest.class.cast(pair.getKey());
    final MessageContext ctx = pair.getValue();
    if (this.forceSignedLogoutRequests && !SAMLBindingSupport.isMessageSigned(ctx)) {
        throw new SAMLException("Logout request is not signed but should be.");
    }
    if (SAMLBindingSupport.isMessageSigned(ctx)) {
        final MetadataResolver resolver = SamlIdPUtils.getMetadataResolverForAllSamlServices(this.servicesManager, SamlIdPUtils.getIssuerFromSamlRequest(logoutRequest), this.samlRegisteredServiceCachingMetadataResolver);
        this.samlObjectSignatureValidator.verifySamlProfileRequestIfNeeded(logoutRequest, resolver, request, ctx);
    }
    SamlUtils.logSamlObject(this.configBean, logoutRequest);
    response.sendRedirect(this.logoutUrl);
}
Also used : LogoutRequest(org.opensaml.saml.saml2.core.LogoutRequest) MessageContext(org.opensaml.messaging.context.MessageContext) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) SAMLException(org.opensaml.saml.common.SAMLException)

Example 10 with MessageContext

use of org.opensaml.messaging.context.MessageContext in project cas by apereo.

the class SSOPostProfileCallbackHandlerController method handleCallbackProfileRequest.

/**
     * Handle callback profile request.
     *
     * @param response the response
     * @param request  the request
     * @throws Exception the exception
     */
@GetMapping(path = SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK)
protected void handleCallbackProfileRequest(final HttpServletResponse response, final HttpServletRequest request) throws Exception {
    LOGGER.info("Received SAML callback profile request [{}]", request.getRequestURI());
    final AuthnRequest authnRequest = retrieveSamlAuthenticationRequestFromHttpRequest(request);
    if (authnRequest == null) {
        LOGGER.error("Can not validate the request because the original Authn request can not be found.");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final String ticket = CommonUtils.safeGetParameter(request, CasProtocolConstants.PARAMETER_TICKET);
    if (StringUtils.isBlank(ticket)) {
        LOGGER.error("Can not validate the request because no [{}] is provided via the request", CasProtocolConstants.PARAMETER_TICKET);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    final Pair<AuthnRequest, MessageContext> authenticationContext = buildAuthenticationContextPair(request, authnRequest);
    final Assertion assertion = validateRequestAndBuildCasAssertion(response, request, authenticationContext);
    buildSamlResponse(response, request, authenticationContext, assertion);
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Assertion(org.jasig.cas.client.validation.Assertion) MessageContext(org.opensaml.messaging.context.MessageContext) GetMapping(org.springframework.web.bind.annotation.GetMapping)

Aggregations

MessageContext (org.opensaml.messaging.context.MessageContext)11 SamlException (org.apereo.cas.support.saml.SamlException)5 SAMLException (org.opensaml.saml.common.SAMLException)4 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)4 UnauthorizedServiceException (org.apereo.cas.services.UnauthorizedServiceException)3 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)2 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)2 SignableSAMLObject (org.opensaml.saml.common.SignableSAMLObject)2 SOAP11Context (org.opensaml.soap.messaging.context.SOAP11Context)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 StringWriter (java.io.StringWriter)1 URLBuilder (net.shibboleth.utilities.java.support.net.URLBuilder)1 Authentication (org.apereo.cas.authentication.Authentication)1 AuthenticationException (org.apereo.cas.authentication.AuthenticationException)1 Credential (org.apereo.cas.authentication.Credential)1 UsernamePasswordCredential (org.apereo.cas.authentication.UsernamePasswordCredential)1 SamlRegisteredServiceCachingMetadataResolver (org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver)1 Assertion (org.jasig.cas.client.validation.Assertion)1 DateTime (org.joda.time.DateTime)1 MessageDecodingException (org.opensaml.messaging.decoder.MessageDecodingException)1