Search in sources :

Example 91 with AuthnRequest

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

the class IdpEndpoint method showLoginPage.

private Response showLoginPage(String samlRequest, String relayState, String signatureAlgorithm, String signature, HttpServletRequest request, Binding binding, String template, String originalBinding) throws WSSecurityException {
    String responseStr;
    AuthnRequest authnRequest = null;
    try {
        Map<String, Object> responseMap = new HashMap<>();
        binding.validator().validateRelayState(relayState);
        authnRequest = binding.decoder().decodeRequest(samlRequest);
        authnRequest.getIssueInstant();
        binding.validator().validateAuthnRequest(authnRequest, samlRequest, relayState, signatureAlgorithm, signature, strictSignature);
        if (!request.isSecure()) {
            throw new IllegalArgumentException("Authn Request must use TLS.");
        }
        X509Certificate[] certs = (X509Certificate[]) request.getAttribute(CERTIFICATES_ATTR);
        boolean hasCerts = (certs != null && certs.length > 0);
        boolean hasCookie = hasValidCookie(request, authnRequest.isForceAuthn());
        if ((authnRequest.isPassive() && hasCerts) || hasCookie) {
            LOGGER.debug("Received Passive & PKI AuthnRequest.");
            org.opensaml.saml.saml2.core.Response samlpResponse;
            try {
                samlpResponse = handleLogin(authnRequest, PKI, request, null, authnRequest.isPassive(), hasCookie);
                LOGGER.debug("Passive & PKI AuthnRequest logged in successfully.");
            } catch (SecurityServiceException e) {
                LOGGER.debug(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.AUTHN_FAILED, binding);
            } catch (WSSecurityException e) {
                LOGGER.debug(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_DENIED, binding);
            } catch (SimpleSign.SignatureException | ConstraintViolationException e) {
                LOGGER.debug(e.getMessage(), e);
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_UNSUPPORTED, binding);
            }
            LOGGER.debug("Returning Passive & PKI SAML Response.");
            NewCookie cookie = null;
            if (hasCookie) {
                cookieCache.addActiveSp(getCookie(request).getValue(), authnRequest.getIssuer().getValue());
            } else {
                cookie = createCookie(request, samlpResponse);
                if (cookie != null) {
                    cookieCache.addActiveSp(cookie.getValue(), authnRequest.getIssuer().getValue());
                }
            }
            logAddedSp(authnRequest);
            return binding.creator().getSamlpResponse(relayState, authnRequest, samlpResponse, cookie, template);
        } else {
            LOGGER.debug("Building the JSON map to embed in the index.html page for login.");
            Document doc = DOMUtils.createDocument();
            doc.appendChild(doc.createElement("root"));
            String authn = DOM2Writer.nodeToString(OpenSAMLUtil.toDom(authnRequest, doc, false));
            String encodedAuthn = RestSecurity.deflateAndBase64Encode(authn);
            responseMap.put(PKI, hasCerts);
            responseMap.put(GUEST, guestAccess);
            responseMap.put(SAML_REQ, encodedAuthn);
            responseMap.put(RELAY_STATE, relayState);
            String assertionConsumerServiceURL = ((ResponseCreatorImpl) binding.creator()).getAssertionConsumerServiceURL(authnRequest);
            responseMap.put(ACS_URL, assertionConsumerServiceURL);
            responseMap.put(SSOConstants.SIG_ALG, signatureAlgorithm);
            responseMap.put(SSOConstants.SIGNATURE, signature);
            responseMap.put(ORIGINAL_BINDING, originalBinding);
        }
        String json = Boon.toJson(responseMap);
        LOGGER.debug("Returning index.html page.");
        responseStr = indexHtml.replace(IDP_STATE_OBJ, json);
        return Response.ok(responseStr).build();
    } catch (IllegalArgumentException e) {
        LOGGER.debug(e.getMessage(), e);
        if (authnRequest != null) {
            try {
                return getErrorResponse(relayState, authnRequest, StatusCode.REQUEST_UNSUPPORTED, binding);
            } catch (IOException | SimpleSign.SignatureException e1) {
                LOGGER.debug(e1.getMessage(), e1);
            }
        }
    } catch (UnsupportedOperationException e) {
        LOGGER.debug(e.getMessage(), e);
        if (authnRequest != null) {
            try {
                return getErrorResponse(relayState, authnRequest, StatusCode.UNSUPPORTED_BINDING, binding);
            } catch (IOException | SimpleSign.SignatureException e1) {
                LOGGER.debug(e1.getMessage(), e1);
            }
        }
    } catch (SimpleSign.SignatureException e) {
        LOGGER.debug("Unable to validate AuthRequest Signature", e);
    } catch (IOException e) {
        LOGGER.debug("Unable to decode AuthRequest", e);
    } catch (ValidationException e) {
        LOGGER.debug("AuthnRequest schema validation failed.", e);
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) ValidationException(ddf.security.samlp.ValidationException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Document(org.w3c.dom.Document) SimpleSign(ddf.security.samlp.SimpleSign) ConstraintViolationException(net.shibboleth.utilities.java.support.logic.ConstraintViolationException) NewCookie(javax.ws.rs.core.NewCookie) ResponseCreatorImpl(org.codice.ddf.security.idp.binding.api.impl.ResponseCreatorImpl) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 92 with AuthnRequest

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

the class SamlIdPUtils method getAssertionConsumerServiceFor.

/**
 * Gets assertion consumer service for.
 *
 * @param authnRequest    the authn request
 * @param servicesManager the services manager
 * @param resolver        the resolver
 * @return the assertion consumer service for
 */
public static AssertionConsumerService getAssertionConsumerServiceFor(final AuthnRequest authnRequest, final ServicesManager servicesManager, final SamlRegisteredServiceCachingMetadataResolver resolver) {
    try {
        final AssertionConsumerService acs = new AssertionConsumerServiceBuilder().buildObject();
        if (authnRequest.getAssertionConsumerServiceIndex() != null) {
            final String issuer = getIssuerFromSamlRequest(authnRequest);
            final MetadataResolver samlResolver = getMetadataResolverForAllSamlServices(servicesManager, issuer, resolver);
            final CriteriaSet criteriaSet = new CriteriaSet();
            criteriaSet.add(new EntityIdCriterion(issuer));
            criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME));
            criteriaSet.add(new BindingCriterion(CollectionUtils.wrap(SAMLConstants.SAML2_POST_BINDING_URI)));
            final Iterable<EntityDescriptor> it = samlResolver.resolve(criteriaSet);
            it.forEach(entityDescriptor -> {
                final SPSSODescriptor spssoDescriptor = entityDescriptor.getSPSSODescriptor(SAMLConstants.SAML20P_NS);
                final List<AssertionConsumerService> acsEndpoints = spssoDescriptor.getAssertionConsumerServices();
                if (acsEndpoints.isEmpty()) {
                    throw new IllegalArgumentException("Metadata resolved for entity id " + issuer + " has no defined ACS endpoints");
                }
                final int acsIndex = authnRequest.getAssertionConsumerServiceIndex();
                if (acsIndex + 1 > acsEndpoints.size()) {
                    throw new IllegalArgumentException("AssertionConsumerService index specified in the request " + acsIndex + " is invalid " + "since the total endpoints available to " + issuer + " is " + acsEndpoints.size());
                }
                final AssertionConsumerService foundAcs = acsEndpoints.get(acsIndex);
                acs.setBinding(foundAcs.getBinding());
                acs.setLocation(foundAcs.getLocation());
                acs.setResponseLocation(foundAcs.getResponseLocation());
                acs.setIndex(acsIndex);
            });
        } else {
            acs.setBinding(authnRequest.getProtocolBinding());
            acs.setLocation(authnRequest.getAssertionConsumerServiceURL());
            acs.setResponseLocation(authnRequest.getAssertionConsumerServiceURL());
            acs.setIndex(0);
            acs.setIsDefault(Boolean.TRUE);
        }
        LOGGER.debug("Resolved AssertionConsumerService from the request is [{}]", acs);
        if (StringUtils.isBlank(acs.getBinding())) {
            throw new SamlException("AssertionConsumerService has no protocol binding defined");
        }
        if (StringUtils.isBlank(acs.getLocation()) && StringUtils.isBlank(acs.getResponseLocation())) {
            throw new SamlException("AssertionConsumerService has no location or response location defined");
        }
        return acs;
    } catch (final Exception e) {
        throw new IllegalArgumentException(new SamlException(e.getMessage(), e));
    }
}
Also used : AssertionConsumerServiceBuilder(org.opensaml.saml.saml2.metadata.impl.AssertionConsumerServiceBuilder) EntityIdCriterion(org.opensaml.core.criterion.EntityIdCriterion) BindingCriterion(org.opensaml.saml.criterion.BindingCriterion) SamlRegisteredServiceCachingMetadataResolver(org.apereo.cas.support.saml.services.idp.metadata.cache.SamlRegisteredServiceCachingMetadataResolver) MetadataResolver(org.opensaml.saml.metadata.resolver.MetadataResolver) ChainingMetadataResolver(org.opensaml.saml.metadata.resolver.ChainingMetadataResolver) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) EntityDescriptor(org.opensaml.saml.saml2.metadata.EntityDescriptor) SPSSODescriptor(org.opensaml.saml.saml2.metadata.SPSSODescriptor) CriteriaSet(net.shibboleth.utilities.java.support.resolver.CriteriaSet) EntityRoleCriterion(org.opensaml.saml.criterion.EntityRoleCriterion) AssertionConsumerService(org.opensaml.saml.saml2.metadata.AssertionConsumerService)

Example 93 with AuthnRequest

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

the class AbstractSamlProfileHandlerController 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 SignableSAMLObject, MessageContext> authenticationContext, final HttpServletRequest request) throws Exception {
    final AuthnRequest authnRequest = AuthnRequest.class.cast(authenticationContext.getKey());
    final String issuer = SamlIdPUtils.getIssuerFromSamlRequest(authnRequest);
    LOGGER.debug("Located issuer [{}] from authentication request", issuer);
    final SamlRegisteredService registeredService = verifySamlRegisteredService(issuer);
    LOGGER.debug("Fetching saml metadata adaptor for [{}]", issuer);
    final Optional<SamlRegisteredServiceServiceProviderMetadataFacade> adaptor = SamlRegisteredServiceServiceProviderMetadataFacade.get(this.samlRegisteredServiceCachingMetadataResolver, registeredService, authnRequest);
    if (!adaptor.isPresent()) {
        LOGGER.warn("No metadata could be found for [{}]", issuer);
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, "Cannot find metadata linked to " + issuer);
    }
    final SamlRegisteredServiceServiceProviderMetadataFacade facade = adaptor.get();
    verifyAuthenticationContextSignature(authenticationContext, request, authnRequest, facade);
    SamlUtils.logSamlObject(this.configBean, authnRequest);
    return Pair.of(registeredService, facade);
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException)

Example 94 with AuthnRequest

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

the class AbstractSamlProfileHandlerController method buildSamlResponse.

/**
 * Build saml response.
 *
 * @param response              the response
 * @param request               the request
 * @param authenticationContext the authentication context
 * @param casAssertion          the cas assertion
 * @param binding               the binding
 */
protected void buildSamlResponse(final HttpServletResponse response, final HttpServletRequest request, final Pair<AuthnRequest, MessageContext> authenticationContext, final Assertion casAssertion, final String binding) {
    final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> pair = getRegisteredServiceAndFacade(authenticationContext.getKey());
    final String entityId = pair.getValue().getEntityId();
    LOGGER.debug("Preparing SAML response for [{}]", entityId);
    final AuthnRequest authnRequest = authenticationContext.getKey();
    this.responseBuilder.build(authnRequest, request, response, casAssertion, pair.getKey(), pair.getValue(), binding);
    LOGGER.info("Built the SAML response for [{}]", entityId);
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService)

Example 95 with AuthnRequest

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

the class SamlProfileSamlAssertionBuilder method build.

@Override
public Assertion build(final RequestAbstractType authnRequest, final HttpServletRequest request, final HttpServletResponse response, final Object casAssertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
    final List<Statement> statements = new ArrayList<>();
    final AuthnStatement authnStatement = this.samlProfileSamlAuthNStatementBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding);
    statements.add(authnStatement);
    final AttributeStatement attrStatement = this.samlProfileSamlAttributeStatementBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding);
    if (!attrStatement.getAttributes().isEmpty() || !attrStatement.getEncryptedAttributes().isEmpty()) {
        statements.add(attrStatement);
    }
    final String id = '_' + String.valueOf(Math.abs(RandomUtils.getNativeInstance().nextLong()));
    final Assertion assertion = newAssertion(statements, casProperties.getAuthn().getSamlIdp().getEntityId(), ZonedDateTime.now(ZoneOffset.UTC), id);
    assertion.setSubject(this.samlProfileSamlSubjectBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding));
    assertion.setConditions(this.samlProfileSamlConditionsBuilder.build(authnRequest, request, response, casAssertion, service, adaptor, binding));
    signAssertion(assertion, request, response, service, adaptor, binding);
    return assertion;
}
Also used : AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) Statement(org.opensaml.saml.saml2.core.Statement) AttributeStatement(org.opensaml.saml.saml2.core.AttributeStatement) ArrayList(java.util.ArrayList) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement) Assertion(org.opensaml.saml.saml2.core.Assertion)

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