Search in sources :

Example 11 with AuthnRequest

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

the class ECPProfileHandlerController method handleEcpRequest.

/**
 * Handle ecp request.
 *
 * @param response    the response
 * @param request     the request
 * @param soapContext the soap context
 * @param credential  the credential
 * @param binding     the binding
 */
protected void handleEcpRequest(final HttpServletResponse response, final HttpServletRequest request, final MessageContext soapContext, final Credential credential, final String binding) {
    LOGGER.debug("Handling ECP request for SOAP context [{}]", soapContext);
    final Envelope envelope = soapContext.getSubcontext(SOAP11Context.class).getEnvelope();
    SamlUtils.logSamlObject(configBean, envelope);
    final AuthnRequest authnRequest = (AuthnRequest) soapContext.getMessage();
    final Pair<AuthnRequest, MessageContext> authenticationContext = Pair.of(authnRequest, soapContext);
    try {
        LOGGER.debug("Verifying ECP authentication request [{}]", authnRequest);
        final Pair<SamlRegisteredService, SamlRegisteredServiceServiceProviderMetadataFacade> serviceRequest = verifySamlAuthenticationRequest(authenticationContext, request);
        LOGGER.debug("Attempting to authenticate ECP request for credential id [{}]", credential.getId());
        final Authentication authentication = authenticateEcpRequest(credential, authenticationContext);
        LOGGER.debug("Authenticated [{}] successfully with authenticated principal [{}]", credential.getId(), authentication.getPrincipal());
        LOGGER.debug("Building ECP SAML response for [{}]", credential.getId());
        final String issuer = SamlIdPUtils.getIssuerFromSamlRequest(authnRequest);
        final Service service = webApplicationServiceFactory.createService(issuer);
        final Assertion casAssertion = buildCasAssertion(authentication, service, serviceRequest.getKey(), new LinkedHashMap<>());
        LOGGER.debug("CAS assertion to use for building ECP SAML response is [{}]", casAssertion);
        buildSamlResponse(response, request, authenticationContext, casAssertion, binding);
    } catch (final AuthenticationException e) {
        LOGGER.error(e.getMessage(), e);
        final String error = e.getHandlerErrors().values().stream().map(Throwable::getMessage).filter(Objects::nonNull).collect(Collectors.joining(","));
        buildEcpFaultResponse(response, request, Pair.of(authnRequest, error));
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        buildEcpFaultResponse(response, request, Pair.of(authnRequest, e.getMessage()));
    }
}
Also used : AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SamlRegisteredServiceServiceProviderMetadataFacade(org.apereo.cas.support.saml.services.idp.metadata.SamlRegisteredServiceServiceProviderMetadataFacade) Assertion(org.jasig.cas.client.validation.Assertion) WebApplicationService(org.apereo.cas.authentication.principal.WebApplicationService) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Service(org.apereo.cas.authentication.principal.Service) Envelope(org.opensaml.soap.soap11.Envelope) AuthenticationException(org.apereo.cas.authentication.AuthenticationException) SOAP11Context(org.opensaml.soap.messaging.context.SOAP11Context) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Authentication(org.apereo.cas.authentication.Authentication) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) Objects(java.util.Objects) MessageContext(org.opensaml.messaging.context.MessageContext)

Example 12 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project cxf by apache.

the class AuthnRequestBuilderTest method testAuthnRequestID.

@org.junit.Test
public void testAuthnRequestID() throws Exception {
    AuthnRequestBuilder authnRequestBuilder = new DefaultAuthnRequestBuilder();
    AuthnRequest authnRequest = authnRequestBuilder.createAuthnRequest(new MessageImpl(), "http://localhost:9001/app", "http://localhost:9001/sso");
    assertTrue("ID must start with a letter or underscore, and can only contain letters, digits, " + "underscores, hyphens, and periods.", authnRequest.getID().matches("^[_a-zA-Z][-_0-9a-zA-Z\\.]+$"));
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) MessageImpl(org.apache.cxf.message.MessageImpl)

Example 13 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project syncope by apache.

the class SAML2SPLogic method createLoginRequest.

@PreAuthorize("hasRole('" + StandardEntitlement.ANONYMOUS + "')")
public SAML2RequestTO createLoginRequest(final String spEntityID, final String idpEntityID) {
    check();
    // 1. look for IdP
    SAML2IdPEntity idp = StringUtils.isBlank(idpEntityID) ? cache.getFirst() : cache.get(idpEntityID);
    if (idp == null) {
        if (StringUtils.isBlank(idpEntityID)) {
            List<SAML2IdP> all = saml2IdPDAO.findAll();
            if (!all.isEmpty()) {
                idp = getIdP(all.get(0).getKey());
            }
        } else {
            idp = getIdP(idpEntityID);
        }
    }
    if (idp == null) {
        throw new NotFoundException(StringUtils.isBlank(idpEntityID) ? "Any SAML 2.0 IdP" : "SAML 2.0 IdP '" + idpEntityID + "'");
    }
    if (idp.getSSOLocation(idp.getBindingType()) == null) {
        throw new IllegalArgumentException("No SingleSignOnService available for " + idp.getId());
    }
    // 2. create AuthnRequest
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue(spEntityID);
    NameIDPolicy nameIDPolicy = new NameIDPolicyBuilder().buildObject();
    if (idp.supportsNameIDFormat(NameIDType.TRANSIENT)) {
        nameIDPolicy.setFormat(NameIDType.TRANSIENT);
    } else if (idp.supportsNameIDFormat(NameIDType.PERSISTENT)) {
        nameIDPolicy.setFormat(NameIDType.PERSISTENT);
    } else {
        throw new IllegalArgumentException("Could not find supported NameIDFormat for IdP " + idpEntityID);
    }
    nameIDPolicy.setAllowCreate(true);
    nameIDPolicy.setSPNameQualifier(spEntityID);
    AuthnContextClassRef authnContextClassRef = new AuthnContextClassRefBuilder().buildObject();
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
    RequestedAuthnContext requestedAuthnContext = new RequestedAuthnContextBuilder().buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setID("_" + UUID_GENERATOR.generate().toString());
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setProtocolBinding(idp.getBindingType().getUri());
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setIssuer(issuer);
    authnRequest.setNameIDPolicy(nameIDPolicy);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);
    authnRequest.setDestination(idp.getSSOLocation(idp.getBindingType()).getLocation());
    SAML2RequestTO requestTO = new SAML2RequestTO();
    requestTO.setIdpServiceAddress(authnRequest.getDestination());
    requestTO.setBindingType(idp.getBindingType());
    try {
        // 3. generate relay state as JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put(JWT_CLAIM_IDP_DEFLATE, idp.isUseDeflateEncoding());
        Triple<String, String, Date> relayState = accessTokenDataBinder.generateJWT(authnRequest.getID(), JWT_RELAY_STATE_DURATION, claims);
        // 4. sign and encode AuthnRequest
        switch(idp.getBindingType()) {
            case REDIRECT:
                requestTO.setRelayState(URLEncoder.encode(relayState.getMiddle(), StandardCharsets.UTF_8.name()));
                requestTO.setContent(URLEncoder.encode(saml2rw.encode(authnRequest, true), StandardCharsets.UTF_8.name()));
                requestTO.setSignAlg(URLEncoder.encode(saml2rw.getSigAlgo(), StandardCharsets.UTF_8.name()));
                requestTO.setSignature(URLEncoder.encode(saml2rw.sign(requestTO.getContent(), requestTO.getRelayState()), StandardCharsets.UTF_8.name()));
                break;
            case POST:
            default:
                requestTO.setRelayState(relayState.getMiddle());
                saml2rw.sign(authnRequest);
                requestTO.setContent(saml2rw.encode(authnRequest, idp.isUseDeflateEncoding()));
        }
    } catch (Exception e) {
        LOG.error("While generating AuthnRequest", e);
        SyncopeClientException sce = SyncopeClientException.build(ClientExceptionType.Unknown);
        sce.getElements().add(e.getMessage());
        throw sce;
    }
    return requestTO;
}
Also used : SAML2RequestTO(org.apache.syncope.common.lib.to.SAML2RequestTO) Issuer(org.opensaml.saml.saml2.core.Issuer) HashMap(java.util.HashMap) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) XSString(org.opensaml.core.xml.schema.XSString) AuthnContextClassRefBuilder(org.opensaml.saml.saml2.core.impl.AuthnContextClassRefBuilder) DateTime(org.joda.time.DateTime) SAML2IdP(org.apache.syncope.core.persistence.api.entity.SAML2IdP) NameIDPolicyBuilder(org.opensaml.saml.saml2.core.impl.NameIDPolicyBuilder) NameIDPolicy(org.opensaml.saml.saml2.core.NameIDPolicy) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) Date(java.util.Date) SyncopeClientException(org.apache.syncope.common.lib.SyncopeClientException) NotFoundException(org.apache.syncope.core.persistence.api.dao.NotFoundException) RequestedAuthnContextBuilder(org.opensaml.saml.saml2.core.impl.RequestedAuthnContextBuilder) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) SAML2IdPEntity(org.apache.syncope.core.logic.saml2.SAML2IdPEntity) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) XMLObject(org.opensaml.core.xml.XMLObject) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Example 14 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project spring-security by spring-projects.

the class OpenSamlAuthenticationRequestFactory method createAuthnRequest.

private AuthnRequest createAuthnRequest(Saml2AuthenticationRequestContext context) {
    String issuer = context.getIssuer();
    String destination = context.getDestination();
    String assertionConsumerServiceUrl = context.getAssertionConsumerServiceUrl();
    Saml2MessageBinding protocolBinding = this.protocolBindingResolver.convert(context);
    AuthnRequest auth = this.authnRequestBuilder.buildObject();
    if (auth.getID() == null) {
        auth.setID("ARQ" + UUID.randomUUID().toString().substring(1));
    }
    if (auth.getIssueInstant() == null) {
        auth.setIssueInstant(new DateTime(this.clock.millis()));
    }
    if (auth.isForceAuthn() == null) {
        auth.setForceAuthn(Boolean.FALSE);
    }
    if (auth.isPassive() == null) {
        auth.setIsPassive(Boolean.FALSE);
    }
    if (auth.getProtocolBinding() == null) {
        auth.setProtocolBinding(protocolBinding.getUrn());
    }
    Issuer iss = this.issuerBuilder.buildObject();
    iss.setValue(issuer);
    auth.setIssuer(iss);
    auth.setDestination(destination);
    auth.setAssertionConsumerServiceURL(assertionConsumerServiceUrl);
    return auth;
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Issuer(org.opensaml.saml.saml2.core.Issuer) Saml2MessageBinding(org.springframework.security.saml2.provider.service.registration.Saml2MessageBinding) DateTime(org.joda.time.DateTime)

Example 15 with AuthnRequest

use of org.opensaml.saml2.core.AuthnRequest in project spring-security by spring-projects.

the class OpenSaml4AuthenticationRequestFactoryTests method createAuthenticationRequestWhenDefaultThenReturnsPostBinding.

@Test
public void createAuthenticationRequestWhenDefaultThenReturnsPostBinding() {
    AuthnRequest authn = getAuthNRequest(Saml2MessageBinding.POST);
    Assertions.assertEquals(SAMLConstants.SAML2_POST_BINDING_URI, authn.getProtocolBinding());
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Test(org.junit.jupiter.api.Test)

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