Search in sources :

Example 1 with AuthnRequestBuilder

use of org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder 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 2 with AuthnRequestBuilder

use of org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder in project cloudstack by apache.

the class SAMLUtils method buildAuthnRequestObject.

public static AuthnRequest buildAuthnRequestObject(final String authnId, final String spId, final String idpUrl, final String consumerUrl) {
    // Issuer object
    IssuerBuilder issuerBuilder = new IssuerBuilder();
    Issuer issuer = issuerBuilder.buildObject();
    issuer.setValue(spId);
    // AuthnContextClass
    AuthnContextClassRefBuilder authnContextClassRefBuilder = new AuthnContextClassRefBuilder();
    AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject(SAMLConstants.SAML20_NS, "AuthnContextClassRef", "saml");
    authnContextClassRef.setAuthnContextClassRef(AuthnContext.PPT_AUTHN_CTX);
    // AuthnContext
    RequestedAuthnContextBuilder requestedAuthnContextBuilder = new RequestedAuthnContextBuilder();
    RequestedAuthnContext requestedAuthnContext = requestedAuthnContextBuilder.buildObject();
    requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT);
    requestedAuthnContext.getAuthnContextClassRefs().add(authnContextClassRef);
    // Creation of AuthRequestObject
    AuthnRequestBuilder authRequestBuilder = new AuthnRequestBuilder();
    AuthnRequest authnRequest = authRequestBuilder.buildObject();
    authnRequest.setID(authnId);
    authnRequest.setDestination(idpUrl);
    authnRequest.setVersion(SAMLVersion.VERSION_20);
    authnRequest.setForceAuthn(false);
    authnRequest.setIsPassive(false);
    authnRequest.setIssueInstant(new DateTime());
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_POST_BINDING_URI);
    authnRequest.setAssertionConsumerServiceURL(consumerUrl);
    authnRequest.setProviderName(spId);
    authnRequest.setIssuer(issuer);
    authnRequest.setRequestedAuthnContext(requestedAuthnContext);
    return authnRequest;
}
Also used : RequestedAuthnContextBuilder(org.opensaml.saml2.core.impl.RequestedAuthnContextBuilder) RequestedAuthnContext(org.opensaml.saml2.core.RequestedAuthnContext) AuthnRequest(org.opensaml.saml2.core.AuthnRequest) Issuer(org.opensaml.saml2.core.Issuer) AuthnContextClassRef(org.opensaml.saml2.core.AuthnContextClassRef) IssuerBuilder(org.opensaml.saml2.core.impl.IssuerBuilder) AuthnRequestBuilder(org.opensaml.saml2.core.impl.AuthnRequestBuilder) AuthnContextClassRefBuilder(org.opensaml.saml2.core.impl.AuthnContextClassRefBuilder) DateTime(org.joda.time.DateTime)

Example 3 with AuthnRequestBuilder

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

the class SSOSamlIdPPostProfileHandlerEndpoint method produce.

private ResponseEntity<Object> produce(final HttpServletRequest request, final HttpServletResponse response, final String username, final String password, final String entityId, final boolean encrypt) {
    try {
        val selectedService = this.serviceFactory.createService(entityId);
        val registeredService = this.servicesManager.findServiceBy(selectedService, SamlRegisteredService.class);
        RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(registeredService);
        val loadedService = (SamlRegisteredService) BeanUtils.cloneBean(registeredService);
        loadedService.setEncryptAssertions(encrypt);
        loadedService.setEncryptAttributes(encrypt);
        val authnRequest = new AuthnRequestBuilder().buildObject();
        authnRequest.setIssuer(saml20ObjectBuilder.newIssuer(entityId));
        val adaptorResult = SamlRegisteredServiceServiceProviderMetadataFacade.get(defaultSamlRegisteredServiceCachingMetadataResolver, loadedService, entityId);
        if (adaptorResult.isPresent()) {
            val adaptor = adaptorResult.get();
            val messageContext = new MessageContext();
            val scratch = messageContext.getSubcontext(ScratchContext.class, true);
            val map = (Map) Objects.requireNonNull(scratch).getMap();
            map.put(SamlProtocolConstants.PARAMETER_ENCODE_RESPONSE, Boolean.FALSE);
            val assertion = getAssertion(username, password, entityId);
            val buildContext = SamlProfileBuilderContext.builder().samlRequest(authnRequest).httpRequest(request).httpResponse(response).authenticatedAssertion(assertion).registeredService(loadedService).adaptor(adaptor).binding(SAMLConstants.SAML2_POST_BINDING_URI).messageContext(messageContext).build();
            val object = responseBuilder.build(buildContext);
            val encoded = SamlUtils.transformSamlObject(saml20ObjectBuilder.getOpenSamlConfigBean(), object, true).toString();
            return new ResponseEntity<>(encoded, HttpStatus.OK);
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
        return new ResponseEntity<>(StringEscapeUtils.escapeHtml4(e.getMessage()), HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Also used : lombok.val(lombok.val) ResponseEntity(org.springframework.http.ResponseEntity) SamlRegisteredService(org.apereo.cas.support.saml.services.SamlRegisteredService) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) MessageContext(org.opensaml.messaging.context.MessageContext) Map(java.util.Map)

Example 4 with AuthnRequestBuilder

use of org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder in project verify-hub by alphagov.

the class AuthnRequestFromRelyingPartyUnmarshallerTest method fromSamlMessage_shouldNotComplainWhenThereIsNoExtensionsElement.

@Test
public void fromSamlMessage_shouldNotComplainWhenThereIsNoExtensionsElement() throws Exception {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setIssuer(new IssuerBuilder().buildObject());
    authnRequest.setDestination("http://example.com");
    AuthnRequestFromRelyingParty authnRequestFromRelyingParty = unmarshaller.fromSamlMessage(authnRequest);
    assertThat(authnRequestFromRelyingParty.getVerifyServiceProviderVersion()).isEqualTo(Optional.empty());
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AuthnRequestFromRelyingParty(uk.gov.ida.saml.hub.domain.AuthnRequestFromRelyingParty) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) Test(org.junit.jupiter.api.Test)

Example 5 with AuthnRequestBuilder

use of org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder in project verify-hub by alphagov.

the class AuthnRequestFromRelyingPartyUnmarshallerTest method fromSamlMessage_shouldNotComplainWhenExceptionDuringDecryption.

@Test
public void fromSamlMessage_shouldNotComplainWhenExceptionDuringDecryption() throws Exception {
    AuthnRequest authnRequest = new AuthnRequestBuilder().buildObject();
    authnRequest.setIssuer(new IssuerBuilder().buildObject());
    authnRequest.setDestination("http://example.com");
    authnRequest.setExtensions(createApplicationVersionExtensions(null));
    AuthnRequestFromRelyingParty authnRequestFromRelyingParty = unmarshaller.fromSamlMessage(authnRequest);
    assertThat(authnRequestFromRelyingParty.getVerifyServiceProviderVersion()).isEqualTo(Optional.empty());
}
Also used : AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) AuthnRequestFromRelyingParty(uk.gov.ida.saml.hub.domain.AuthnRequestFromRelyingParty) AuthnRequestBuilder(org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder) IssuerBuilder(org.opensaml.saml.saml2.core.impl.IssuerBuilder) Test(org.junit.jupiter.api.Test)

Aggregations

AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)7 AuthnRequestBuilder (org.opensaml.saml.saml2.core.impl.AuthnRequestBuilder)5 DateTime (org.joda.time.DateTime)4 IssuerBuilder (org.opensaml.saml.saml2.core.impl.IssuerBuilder)4 Test (org.junit.jupiter.api.Test)3 AuthnRequestFromRelyingParty (uk.gov.ida.saml.hub.domain.AuthnRequestFromRelyingParty)3 MessageImpl (org.apache.cxf.message.MessageImpl)2 Issuer (org.opensaml.saml.saml2.core.Issuer)2 Date (java.util.Date)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 lombok.val (lombok.val)1 Message (org.apache.cxf.message.Message)1 SyncopeClientException (org.apache.syncope.common.lib.SyncopeClientException)1 SAML2RequestTO (org.apache.syncope.common.lib.to.SAML2RequestTO)1 SAML2IdPEntity (org.apache.syncope.core.logic.saml2.SAML2IdPEntity)1 NotFoundException (org.apache.syncope.core.persistence.api.dao.NotFoundException)1 SAML2IdP (org.apache.syncope.core.persistence.api.entity.SAML2IdP)1 SamlRegisteredService (org.apereo.cas.support.saml.services.SamlRegisteredService)1 XMLObject (org.opensaml.core.xml.XMLObject)1