Search in sources :

Example 51 with AuthnRequestType

use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.

the class CreateAuthnRequestStepBuilder method createLoginRequestDocument.

protected Document createLoginRequestDocument() {
    if (this.forceLoginRequestDocument != null) {
        return this.forceLoginRequestDocument;
    }
    try {
        SAML2Request samlReq = new SAML2Request();
        AuthnRequestType loginReq = samlReq.createAuthnRequestType(UUID.randomUUID().toString(), assertionConsumerURL, this.authServerSamlUrl.toString(), issuer, requestBinding.getBindingUri());
        if (protocolBinding != null) {
            loginReq.setProtocolBinding(protocolBinding);
        }
        return SAML2Request.convert(loginReq);
    } catch (ConfigurationException | ParsingException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
Also used : AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) SAML2Request(org.keycloak.saml.processing.api.saml.v2.request.SAML2Request) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Example 52 with AuthnRequestType

use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.

the class KcSamlCustomEntityIdBrokerTest method testCustomEntityNotSet.

@Test
public void testCustomEntityNotSet() throws Exception {
    // No comparison type, no classrefs, no declrefs -> No RequestedAuthnContext
    try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource).update()) {
        // Build the login request document
        AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
        Document doc = SAML2Request.convert(loginRep);
        new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
        Binding.POST).targetAttributeSamlRequest().transformDocument((document) -> {
            try {
                log.infof("Document: %s", DocumentUtil.asString(document));
                // Find the Issuer element
                Element issuerElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), ASSERTION_NSURI.get(), "Issuer");
                Assert.assertEquals("Unexpected Issuer element value", getAuthServerRoot() + "realms/consumer", issuerElement.getTextContent());
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }).build().execute();
    }
}
Also used : AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) Closeable(java.io.Closeable) IdentityProviderAttributeUpdater(org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 53 with AuthnRequestType

use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.

the class KcSamlEncryptedIdTest method testEncryptedIdIsReadable.

@Test
public void testEncryptedIdIsReadable() throws ConfigurationException, ParsingException, ProcessingException {
    createRolesForRealm(bc.consumerRealmName());
    AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
    Document doc = SAML2Request.convert(loginRep);
    final AtomicReference<String> username = new AtomicReference<>();
    assertThat(adminClient.realm(bc.consumerRealmName()).users().search(username.get()), hasSize(0));
    SAMLDocumentHolder samlResponse = new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, SamlClient.Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
    SamlClient.Binding.POST).targetAttributeSamlRequest().build().login().user(bc.getUserLogin(), bc.getUserPassword()).build().processSamlResponse(// Response from producer IdP
    SamlClient.Binding.POST).transformDocument(document -> {
        // Replace Subject -> NameID with EncryptedId
        Node assertionElement = document.getDocumentElement().getElementsByTagNameNS(ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()).item(0);
        if (assertionElement == null) {
            throw new IllegalStateException("Unable to find assertion in saml response document");
        }
        String samlNSPrefix = assertionElement.getPrefix();
        try {
            QName encryptedIdElementQName = new QName(ASSERTION_NSURI.get(), JBossSAMLConstants.ENCRYPTED_ID.get(), samlNSPrefix);
            QName nameIdQName = new QName(ASSERTION_NSURI.get(), JBossSAMLConstants.NAMEID.get(), samlNSPrefix);
            // Add xmlns:saml attribute to NameId element,
            // this is necessary as it is decrypted as a separate doc and saml namespace is not know
            // unless added to NameId element
            Element nameIdElement = DocumentUtil.getElement(document, nameIdQName);
            if (nameIdElement == null) {
                throw new RuntimeException("Assertion doesn't contain NameId " + DocumentUtil.asString(document));
            }
            nameIdElement.setAttribute("xmlns:" + samlNSPrefix, ASSERTION_NSURI.get());
            username.set(nameIdElement.getTextContent());
            byte[] secret = RandomSecret.createRandomSecret(128 / 8);
            SecretKey secretKey = new SecretKeySpec(secret, "AES");
            // encrypt the Assertion element and replace it with a EncryptedAssertion element.
            XMLEncryptionUtil.encryptElement(nameIdQName, document, PemUtils.decodePublicKey(ApiUtil.findActiveSigningKey(adminClient.realm(bc.consumerRealmName())).getPublicKey()), secretKey, 128, encryptedIdElementQName, true);
        } catch (Exception e) {
            throw new ProcessingException("failed to encrypt", e);
        }
        assertThat(DocumentUtil.asString(document), not(containsString(username.get())));
        return document;
    }).build().updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).build().followOneRedirect().getSamlResponse(// Response from consumer IdP
    SamlClient.Binding.POST);
    assertThat(samlResponse, Matchers.notNullValue());
    assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    assertThat(adminClient.realm(bc.consumerRealmName()).users().search(username.get()), hasSize(1));
}
Also used : SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) Document(org.w3c.dom.Document) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) SecretKey(javax.crypto.SecretKey) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) Test(org.junit.Test)

Example 54 with AuthnRequestType

use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.

the class KcSamlLogoutTest method testProviderInitiatedLogoutCorrectlyLogsOutConsumerClients.

@Test
public void testProviderInitiatedLogoutCorrectlyLogsOutConsumerClients() throws Exception {
    try (SamlMessageReceiver logoutReceiver = new SamlMessageReceiver(8082);
        ClientAttributeUpdater cauConsumer = ClientAttributeUpdater.forClient(adminClient, bc.consumerRealmName(), AbstractSamlTest.SAML_CLIENT_ID_SALES_POST).setFrontchannelLogout(false).setAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, logoutReceiver.getUrl()).update();
        ClientAttributeUpdater cauProvider = ClientAttributeUpdater.forClient(adminClient, bc.providerRealmName(), bc.getIDPClientIdInProviderRealm()).setFrontchannelLogout(true).update()) {
        AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);
        Document doc = SAML2Request.convert(loginRep);
        final AtomicReference<NameIDType> nameIdRef = new AtomicReference<>();
        final AtomicReference<String> sessionIndexRef = new AtomicReference<>();
        new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, SamlClient.Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
        SamlClient.Binding.POST).targetAttributeSamlRequest().build().login().user(bc.getUserLogin(), bc.getUserPassword()).build().processSamlResponse(// Response from producer IdP
        SamlClient.Binding.POST).build().updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build().followOneRedirect().processSamlResponse(SamlClient.Binding.POST).transformObject(saml2Object -> {
            assertThat(saml2Object, Matchers.notNullValue());
            assertThat(saml2Object, isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
            return null;
        }).build().authnRequest(getProviderSamlEndpoint(bc.providerRealmName()), PROVIDER_SAML_CLIENT_ID, PROVIDER_SAML_CLIENT_ID + "saml", POST).build().followOneRedirect().processSamlResponse(POST).transformObject(saml2Object -> {
            assertThat(saml2Object, isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
            ResponseType loginResp1 = (ResponseType) saml2Object;
            final AssertionType firstAssertion = loginResp1.getAssertions().get(0).getAssertion();
            assertThat(firstAssertion, Matchers.notNullValue());
            assertThat(firstAssertion.getSubject().getSubType().getBaseID(), instanceOf(NameIDType.class));
            NameIDType nameId = (NameIDType) firstAssertion.getSubject().getSubType().getBaseID();
            AuthnStatementType firstAssertionStatement = (AuthnStatementType) firstAssertion.getStatements().iterator().next();
            nameIdRef.set(nameId);
            sessionIndexRef.set(firstAssertionStatement.getSessionIndex());
            return null;
        }).build().logoutRequest(getProviderSamlEndpoint(bc.providerRealmName()), PROVIDER_SAML_CLIENT_ID, POST).nameId(nameIdRef::get).sessionIndex(sessionIndexRef::get).build().processSamlResponse(POST).transformObject(saml2Object -> {
            assertThat(saml2Object, isSamlLogoutRequest(getConsumerRoot() + "/auth/realms/" + REALM_CONS_NAME + "/broker/" + IDP_SAML_ALIAS + "/endpoint"));
            return saml2Object;
        }).build().executeAndTransform(response -> {
            SAMLDocumentHolder saml2ObjectHolder = POST.extractResponse(response);
            assertThat(saml2ObjectHolder.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
            return null;
        });
        // Check whether logoutReceiver contains correct LogoutRequest
        assertThat(logoutReceiver.isMessageReceived(), is(true));
        SAMLDocumentHolder message = logoutReceiver.getSamlDocumentHolder();
        assertThat(message.getSamlObject(), isSamlLogoutRequest(logoutReceiver.getUrl()));
    }
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) ClientAttributeUpdater(org.keycloak.testsuite.updaters.ClientAttributeUpdater) IDP_SAML_ALIAS(org.keycloak.testsuite.broker.BrokerTestConstants.IDP_SAML_ALIAS) SAML2Request(org.keycloak.saml.processing.api.saml.v2.request.SAML2Request) IdentityProviderAttributeUpdater(org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) SamlConfigAttributes(org.keycloak.protocol.saml.SamlConfigAttributes) POST(org.keycloak.testsuite.util.SamlClient.Binding.POST) Matchers.isSamlLogoutRequest(org.keycloak.testsuite.util.Matchers.isSamlLogoutRequest) AtomicReference(java.util.concurrent.atomic.AtomicReference) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) BrokerTestTools.getConsumerRoot(org.keycloak.testsuite.broker.BrokerTestTools.getConsumerRoot) SAMLIdentityProviderConfig(org.keycloak.broker.saml.SAMLIdentityProviderConfig) AuthnStatementType(org.keycloak.dom.saml.v2.assertion.AuthnStatementType) Document(org.w3c.dom.Document) SamlClient(org.keycloak.testsuite.util.SamlClient) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) Matchers.isSamlResponse(org.keycloak.testsuite.util.Matchers.isSamlResponse) AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) SamlProtocol(org.keycloak.protocol.saml.SamlProtocol) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) List(java.util.List) UserAttributeUpdater(org.keycloak.testsuite.updaters.UserAttributeUpdater) REALM_CONS_NAME(org.keycloak.testsuite.broker.BrokerTestConstants.REALM_CONS_NAME) Closeable(java.io.Closeable) ATTRIBUTE_TO_MAP_NAME(org.keycloak.testsuite.broker.KcOidcBrokerConfiguration.ATTRIBUTE_TO_MAP_NAME) ClientBuilder(org.keycloak.testsuite.util.ClientBuilder) Matchers.isSamlStatusResponse(org.keycloak.testsuite.util.Matchers.isSamlStatusResponse) SamlMessageReceiver(org.keycloak.testsuite.util.saml.SamlMessageReceiver) BrokerTestTools.getProviderRoot(org.keycloak.testsuite.broker.BrokerTestTools.getProviderRoot) SamlPrincipalType(org.keycloak.protocol.saml.SamlPrincipalType) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Document(org.w3c.dom.Document) SamlMessageReceiver(org.keycloak.testsuite.util.saml.SamlMessageReceiver) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) ClientAttributeUpdater(org.keycloak.testsuite.updaters.ClientAttributeUpdater) AuthnStatementType(org.keycloak.dom.saml.v2.assertion.AuthnStatementType) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 55 with AuthnRequestType

use of org.keycloak.dom.saml.v2.protocol.AuthnRequestType in project keycloak by keycloak.

the class KcSamlRequestedAuthnContextBrokerTest method testComparisonTypeSetClassRefsSetNoDeclRefs.

@Test
public void testComparisonTypeSetClassRefsSetNoDeclRefs() throws Exception {
    // Comparison type set, classref present, no declrefs -> RequestedAuthnContext with AuthnContextClassRef
    try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource).setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_COMPARISON_TYPE, AuthnContextComparisonType.EXACT.value()).setAttribute(SAMLIdentityProviderConfig.AUTHN_CONTEXT_CLASS_REFS, "[\"" + AC_PASSWORD_PROTECTED_TRANSPORT.get() + "\"]").update()) {
        // Build the login request document
        AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST + ".dot/ted", getConsumerRoot() + "/sales-post/saml", null);
        Document doc = SAML2Request.convert(loginRep);
        new SamlClientBuilder().authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build().login().idp(bc.getIDPAlias()).build().processSamlResponse(// AuthnRequest to producer IdP
        Binding.POST).targetAttributeSamlRequest().transformDocument((document) -> {
            try {
                log.infof("Document: %s", DocumentUtil.asString(document));
                // Find the RequestedAuthnContext element
                Element requestedAuthnContextElement = DocumentUtil.getDirectChildElement(document.getDocumentElement(), PROTOCOL_NSURI.get(), "RequestedAuthnContext");
                Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement, Matchers.notNullValue());
                // Verify the ComparisonType attribute
                Assert.assertThat("RequestedAuthnContext element not found in request document", requestedAuthnContextElement.getAttribute("Comparison"), Matchers.is(AuthnContextComparisonType.EXACT.value()));
                // Find the RequestedAuthnContext/ClassRef element
                Element requestedAuthnContextClassRefElement = DocumentUtil.getDirectChildElement(requestedAuthnContextElement, ASSERTION_NSURI.get(), "AuthnContextClassRef");
                Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element not found in request document", requestedAuthnContextClassRefElement, Matchers.notNullValue());
                // Make sure the RequestedAuthnContext/ClassRef element has the requested value
                Assert.assertThat("RequestedAuthnContext/AuthnContextClassRef element does not have the expected value", requestedAuthnContextClassRefElement.getTextContent(), Matchers.is(AC_PASSWORD_PROTECTED_TRANSPORT.get()));
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }).build().execute();
    }
}
Also used : AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) Closeable(java.io.Closeable) IdentityProviderAttributeUpdater(org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Aggregations

AuthnRequestType (org.keycloak.dom.saml.v2.protocol.AuthnRequestType)56 Test (org.junit.Test)41 Document (org.w3c.dom.Document)36 SamlClientBuilder (org.keycloak.testsuite.util.SamlClientBuilder)30 AbstractSamlTest (org.keycloak.testsuite.saml.AbstractSamlTest)21 Element (org.w3c.dom.Element)16 Closeable (java.io.Closeable)13 SAMLDocumentHolder (org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder)13 IdentityProviderAttributeUpdater (org.keycloak.testsuite.updaters.IdentityProviderAttributeUpdater)13 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)10 ConfigurationException (org.keycloak.saml.common.exceptions.ConfigurationException)8 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)7 StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)7 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)7 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 Matchers.containsString (org.hamcrest.Matchers.containsString)5 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)5 SAML2Request (org.keycloak.saml.processing.api.saml.v2.request.SAML2Request)4 URI (java.net.URI)3