Search in sources :

Example 86 with AuthnRequest

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

the class SamlProfileSamlNameIdBuilder method buildNameId.

/**
     * Build name id.
     * If there are no explicitly defined NameIDFormats, include the default format.
     * see: http://saml2int.org/profile/current/#section92
     *
     * @param authnRequest the authn request
     * @param assertion    the assertion
     * @param service      the service
     * @param adaptor      the adaptor
     * @return the name id
     * @throws SamlException the saml exception
     */
private NameID buildNameId(final AuthnRequest authnRequest, final Assertion assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final List<String> supportedNameFormats = adaptor.getSupportedNameIdFormats();
    LOGGER.debug("Metadata for [{}] declares support for the following NameIDs [{}]", adaptor.getEntityId(), supportedNameFormats);
    if (supportedNameFormats.isEmpty()) {
        supportedNameFormats.add(NameIDType.TRANSIENT);
        LOGGER.debug("No supported nameId formats could be determined from metadata. Added default [{}]", NameIDType.TRANSIENT);
    }
    if (StringUtils.isNotBlank(service.getRequiredNameIdFormat())) {
        final String fmt = parseAndBuildRequiredNameIdFormat(service);
        supportedNameFormats.add(0, fmt);
        LOGGER.debug("Added required nameId format [{}] based on saml service configuration for [{}]", fmt, service.getServiceId());
    }
    String requiredNameFormat = null;
    if (authnRequest.getNameIDPolicy() != null) {
        requiredNameFormat = authnRequest.getNameIDPolicy().getFormat();
        LOGGER.debug("AuthN request indicates [{}] is the required NameID format", requiredNameFormat);
        if (NameID.ENCRYPTED.equals(requiredNameFormat)) {
            LOGGER.warn("Encrypted NameID formats are not supported");
            requiredNameFormat = null;
        }
    }
    if (StringUtils.isNotBlank(requiredNameFormat) && !supportedNameFormats.contains(requiredNameFormat)) {
        LOGGER.warn("Required NameID format [{}] in the AuthN request issued by [{}] is not supported based on the metadata for [{}]", requiredNameFormat, SamlIdPUtils.getIssuerFromSamlRequest(authnRequest), adaptor.getEntityId());
        throw new SamlException("Required NameID format cannot be provided because it is not supported");
    }
    for (final String nameFormat : supportedNameFormats) {
        try {
            LOGGER.debug("Evaluating NameID format [{}]", nameFormat);
            final SAML2StringNameIDEncoder encoder = new SAML2StringNameIDEncoder();
            encoder.setNameFormat(nameFormat);
            if (authnRequest.getNameIDPolicy() != null) {
                final String qualifier = authnRequest.getNameIDPolicy().getSPNameQualifier();
                LOGGER.debug("NameID qualifier is set to [{}]", qualifier);
                encoder.setNameQualifier(qualifier);
            }
            final IdPAttribute attribute = new IdPAttribute(AttributePrincipal.class.getName());
            final IdPAttributeValue<String> value = new StringAttributeValue(assertion.getPrincipal().getName());
            LOGGER.debug("NameID attribute value is set to [{}]", assertion.getPrincipal().getName());
            attribute.setValues(Collections.singletonList(value));
            LOGGER.debug("Encoding NameID based on [{}]", nameFormat);
            final NameID nameid = encoder.encode(attribute);
            LOGGER.debug("Final NameID encoded is [{}] with value [{}]", nameid.getFormat(), nameid.getValue());
            return nameid;
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
    return null;
}
Also used : NameID(org.opensaml.saml.saml2.core.NameID) SamlException(org.apereo.cas.support.saml.SamlException) IdPAttribute(net.shibboleth.idp.attribute.IdPAttribute) StringAttributeValue(net.shibboleth.idp.attribute.StringAttributeValue) SAML2StringNameIDEncoder(net.shibboleth.idp.saml.attribute.encoding.impl.SAML2StringNameIDEncoder) AttributePrincipal(org.jasig.cas.client.authentication.AttributePrincipal) SamlException(org.apereo.cas.support.saml.SamlException)

Example 87 with AuthnRequest

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

the class SamlProfileSamlSubjectBuilder method buildSubject.

private Subject buildSubject(final HttpServletRequest request, final HttpServletResponse response, final AuthnRequest authnRequest, final Assertion assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final NameID nameID = this.ssoPostProfileSamlNameIdBuilder.build(authnRequest, request, response, assertion, service, adaptor);
    final ZonedDateTime validFromDate = ZonedDateTime.ofInstant(assertion.getValidFromDate().toInstant(), ZoneOffset.UTC);
    final Subject subject = newSubject(nameID.getFormat(), nameID.getValue(), authnRequest.getAssertionConsumerServiceURL(), validFromDate.plusSeconds(this.skewAllowance), authnRequest.getID());
    subject.setNameID(nameID);
    return subject;
}
Also used : NameID(org.opensaml.saml.saml2.core.NameID) ZonedDateTime(java.time.ZonedDateTime) Subject(org.opensaml.saml.saml2.core.Subject)

Example 88 with AuthnRequest

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

the class SamlProfileSamlSoap11ResponseBuilder method buildResponse.

@Override
protected Envelope buildResponse(final Assertion assertion, final org.jasig.cas.client.validation.Assertion casAssertion, final AuthnRequest authnRequest, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final HttpServletRequest request, final HttpServletResponse response) throws SamlException {
    final Response ecpResponse = newEcpResponse(adaptor.getAssertionConsumerService().getLocation());
    final Header header = newSoapObject(Header.class);
    header.getUnknownXMLObjects().add(ecpResponse);
    final Body body = newSoapObject(Body.class);
    final org.opensaml.saml.saml2.core.Response saml2Response = (org.opensaml.saml.saml2.core.Response) saml2ResponseBuilder.build(authnRequest, request, response, casAssertion, service, adaptor);
    body.getUnknownXMLObjects().add(saml2Response);
    final Envelope envelope = newSoapObject(Envelope.class);
    envelope.setHeader(header);
    envelope.setBody(body);
    return envelope;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.opensaml.saml.saml2.ecp.Response) Header(org.opensaml.soap.soap11.Header) Envelope(org.opensaml.soap.soap11.Envelope) Body(org.opensaml.soap.soap11.Body)

Example 89 with AuthnRequest

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

Example 90 with AuthnRequest

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

the class IdpEndpoint method processLogin.

@GET
@Path("/login/sso")
public Response processLogin(@QueryParam(SAML_REQ) String samlRequest, @QueryParam(RELAY_STATE) String relayState, @QueryParam(AUTH_METHOD) String authMethod, @QueryParam(SSOConstants.SIG_ALG) String signatureAlgorithm, @QueryParam(SSOConstants.SIGNATURE) String signature, @QueryParam(ORIGINAL_BINDING) String originalBinding, @Context HttpServletRequest request) {
    LOGGER.debug("Processing login request: [ authMethod {} ], [ sigAlg {} ], [ relayState {} ]", authMethod, signatureAlgorithm, relayState);
    try {
        Binding binding;
        String template;
        if (!request.isSecure()) {
            throw new IllegalArgumentException("Authn Request must use TLS.");
        }
        //the authn request is always encoded as if it came in via redirect when coming from the web app
        Binding redirectBinding = new RedirectBinding(systemCrypto, serviceProviders);
        AuthnRequest authnRequest = redirectBinding.decoder().decodeRequest(samlRequest);
        String assertionConsumerServiceBinding = ResponseCreator.getAssertionConsumerServiceBinding(authnRequest, serviceProviders);
        if (HTTP_POST_BINDING.equals(originalBinding)) {
            binding = new PostBinding(systemCrypto, serviceProviders);
            template = submitForm;
        } else if (HTTP_REDIRECT_BINDING.equals(originalBinding)) {
            binding = redirectBinding;
            template = redirectPage;
        } else {
            throw new IdpException(new UnsupportedOperationException("Must use HTTP POST or Redirect bindings."));
        }
        binding.validator().validateAuthnRequest(authnRequest, samlRequest, relayState, signatureAlgorithm, signature, strictSignature);
        if (HTTP_POST_BINDING.equals(assertionConsumerServiceBinding)) {
            if (!(binding instanceof PostBinding)) {
                binding = new PostBinding(systemCrypto, serviceProviders);
            }
        } else if (HTTP_REDIRECT_BINDING.equals(assertionConsumerServiceBinding)) {
            if (!(binding instanceof RedirectBinding)) {
                binding = new RedirectBinding(systemCrypto, serviceProviders);
            }
        }
        org.opensaml.saml.saml2.core.Response encodedSaml = handleLogin(authnRequest, authMethod, request, null, false, false);
        LOGGER.debug("Returning SAML Response for relayState: {}" + relayState);
        NewCookie newCookie = createCookie(request, encodedSaml);
        Response response = binding.creator().getSamlpResponse(relayState, authnRequest, encodedSaml, newCookie, template);
        if (newCookie != null) {
            cookieCache.addActiveSp(newCookie.getValue(), authnRequest.getIssuer().getValue());
            logAddedSp(authnRequest);
        }
        return response;
    } catch (SecurityServiceException e) {
        LOGGER.info("Unable to retrieve subject for user.", e);
        return Response.status(Response.Status.UNAUTHORIZED).build();
    } catch (WSSecurityException e) {
        LOGGER.info("Unable to encode SAMLP response.", e);
    } catch (SimpleSign.SignatureException e) {
        LOGGER.info("Unable to sign SAML response.", e);
    } catch (IllegalArgumentException e) {
        LOGGER.info(e.getMessage(), e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (ValidationException e) {
        LOGGER.info("AuthnRequest schema validation failed.", e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    } catch (IOException e) {
        LOGGER.info("Unable to create SAML Response.", e);
    } catch (IdpException e) {
        LOGGER.info(e.getMessage(), e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
Also used : RedirectBinding(org.codice.ddf.security.idp.binding.redirect.RedirectBinding) SoapBinding(org.codice.ddf.security.idp.binding.soap.SoapBinding) Binding(org.codice.ddf.security.idp.binding.api.Binding) PostBinding(org.codice.ddf.security.idp.binding.post.PostBinding) RedirectBinding(org.codice.ddf.security.idp.binding.redirect.RedirectBinding) SecurityServiceException(ddf.security.service.SecurityServiceException) ValidationException(ddf.security.samlp.ValidationException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) LogoutResponse(org.opensaml.saml.saml2.core.LogoutResponse) Response(javax.ws.rs.core.Response) SimpleSign(ddf.security.samlp.SimpleSign) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) PostBinding(org.codice.ddf.security.idp.binding.post.PostBinding) NewCookie(javax.ws.rs.core.NewCookie) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

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