Search in sources :

Example 36 with Request

use of org.opensaml.saml.saml2.ecp.Request 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 37 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class AbstractSamlProfileHandlerController method decodeSoapRequest.

/**
 * Decode soap 11 context.
 *
 * @param request the request
 * @return the soap 11 context
 */
protected MessageContext decodeSoapRequest(final HttpServletRequest request) {
    try {
        final HTTPSOAP11Decoder decoder = new HTTPSOAP11Decoder();
        decoder.setParserPool(parserPool);
        decoder.setHttpServletRequest(request);
        final BindingDescriptor binding = new BindingDescriptor();
        binding.setId(getClass().getName());
        binding.setShortName(getClass().getName());
        binding.setSignatureCapable(true);
        binding.setSynchronous(true);
        decoder.setBindingDescriptor(binding);
        decoder.initialize();
        decoder.decode();
        return decoder.getMessageContext();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
Also used : BindingDescriptor(org.opensaml.saml.common.binding.BindingDescriptor) SamlException(org.apereo.cas.support.saml.SamlException) SAMLException(org.opensaml.saml.common.SAMLException) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) HTTPSOAP11Decoder(org.opensaml.saml.saml2.binding.decoding.impl.HTTPSOAP11Decoder)

Example 38 with Request

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

Example 39 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlProfileSamlAuthNStatementBuilder method buildAuthnStatement.

/**
 * Creates an authentication statement for the current request.
 *
 * @param assertion    the assertion
 * @param authnRequest the authn request
 * @param adaptor      the adaptor
 * @param service      the service
 * @param binding      the binding
 * @return constructed authentication statement
 * @throws SamlException the saml exception
 */
private AuthnStatement buildAuthnStatement(final Object casAssertion, final RequestAbstractType authnRequest, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final SamlRegisteredService service, final String binding) throws SamlException {
    final Assertion assertion = Assertion.class.cast(casAssertion);
    final String authenticationMethod = this.authnContextClassRefBuilder.build(assertion, authnRequest, adaptor, service);
    final String id = '_' + String.valueOf(Math.abs(RandomUtils.getNativeInstance().nextLong()));
    final AuthnStatement statement = newAuthnStatement(authenticationMethod, DateTimeUtils.zonedDateTimeOf(assertion.getAuthenticationDate()), id);
    if (assertion.getValidUntilDate() != null) {
        final ZonedDateTime dt = DateTimeUtils.zonedDateTimeOf(assertion.getValidUntilDate());
        statement.setSessionNotOnOrAfter(DateTimeUtils.dateTimeOf(dt.plusSeconds(casProperties.getAuthn().getSamlIdp().getResponse().getSkewAllowance())));
    }
    statement.setSubjectLocality(buildSubjectLocality(assertion, authnRequest, adaptor, binding));
    return statement;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) Assertion(org.jasig.cas.client.validation.Assertion) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement)

Example 40 with Request

use of org.opensaml.saml.saml2.ecp.Request in project cas by apereo.

the class SamlProfileSamlConditionsBuilder method buildConditions.

/**
 * Build conditions conditions.
 *
 * @param authnRequest the authn request
 * @param assertion    the assertion
 * @param service      the service
 * @param adaptor      the adaptor
 * @return the conditions
 * @throws SamlException the saml exception
 */
protected Conditions buildConditions(final RequestAbstractType authnRequest, final Object assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    int skewAllowance = casProperties.getAuthn().getSamlIdp().getResponse().getSkewAllowance();
    if (skewAllowance <= 0) {
        skewAllowance = casProperties.getSamlCore().getSkewAllowance();
    }
    final List<String> audienceUrls = new ArrayList<>();
    audienceUrls.add(adaptor.getEntityId());
    if (StringUtils.isNotBlank(service.getAssertionAudiences())) {
        final Set<String> audiences = org.springframework.util.StringUtils.commaDelimitedListToSet(service.getAssertionAudiences());
        audienceUrls.addAll(audiences);
    }
    final Conditions conditions = newConditions(currentDateTime, currentDateTime.plusSeconds(skewAllowance), audienceUrls.toArray(new String[] {}));
    return conditions;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) ArrayList(java.util.ArrayList) Conditions(org.opensaml.saml.saml2.core.Conditions)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)24 IOException (java.io.IOException)13 LogoutResponse (org.opensaml.saml.saml2.core.LogoutResponse)13 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)12 SamlRegisteredServiceServiceProviderMetadataFacade (org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade)11 Test (org.junit.Test)10 ValidationException (ddf.security.samlp.ValidationException)9 Response (javax.ws.rs.core.Response)9 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)9 Assertion (org.jasig.cas.client.validation.Assertion)9 MessageContext (org.opensaml.messaging.context.MessageContext)9 Assertion (org.opensaml.saml.saml2.core.Assertion)9 Document (org.w3c.dom.Document)9 XMLStreamException (javax.xml.stream.XMLStreamException)8 LogoutRequest (org.opensaml.saml.saml2.core.LogoutRequest)8 NameID (org.opensaml.saml.saml2.core.NameID)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 SimpleSign (ddf.security.samlp.SimpleSign)5 ZonedDateTime (java.time.ZonedDateTime)5 Path (javax.ws.rs.Path)5