Search in sources :

Example 51 with SAMLDocumentHolder

use of org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder in project keycloak by keycloak.

the class ArtifactBindingWithResolutionServiceTest method testReceiveArtifactLoginFullWithPost.

@Test
public void testReceiveArtifactLoginFullWithPost() throws ParsingException, ConfigurationException, ProcessingException, InterruptedException {
    getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST).setAttribute(SamlProtocol.SAML_ARTIFACT_RESOLUTION_SERVICE_URL_ATTRIBUTE, "http://127.0.0.1:8082/").update());
    AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(SAML_CLIENT_ID_SALES_POST, AbstractSamlTest.SAML_ASSERTION_CONSUMER_URL_SALES_POST, null);
    Document doc = SAML2Request.convert(loginRep);
    SamlClientBuilder builder = new SamlClientBuilder();
    CreateArtifactMessageStepBuilder camb = new CreateArtifactMessageStepBuilder(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SamlClient.Binding.POST, builder);
    ArtifactResolutionService ars = new ArtifactResolutionService("http://127.0.0.1:8082/").setResponseDocument(doc);
    Thread arsThread = new Thread(ars);
    try {
        arsThread.start();
        synchronized (ars) {
            ars.wait();
            SAMLDocumentHolder response = builder.artifactMessage(camb).build().login().user(bburkeUser).build().getSamlResponse(SamlClient.Binding.POST);
            assertThat(response.getSamlObject(), instanceOf(ResponseType.class));
            ResponseType rt = (ResponseType) response.getSamlObject();
            assertThat(rt.getAssertions(), not(empty()));
            assertThat(ars.getLastArtifactResolve(), notNullValue());
            assertThat(camb.getLastArtifact(), is(ars.getLastArtifactResolve().getArtifact()));
        }
    } finally {
        ars.stop();
        arsThread.join();
    }
}
Also used : SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) ArtifactResolutionService(org.keycloak.testsuite.util.ArtifactResolutionService) Document(org.w3c.dom.Document) CreateArtifactMessageStepBuilder(org.keycloak.testsuite.util.saml.CreateArtifactMessageStepBuilder) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Test(org.junit.Test)

Example 52 with SAMLDocumentHolder

use of org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder in project keycloak by keycloak.

the class ArtifactBindingWithResolutionServiceTest method testReceiveArtifactLogoutFullWithRedirect.

@Test
public void testReceiveArtifactLogoutFullWithRedirect() throws InterruptedException {
    getCleanup().addCleanup(ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST).setAttribute(SamlProtocol.SAML_ARTIFACT_RESOLUTION_SERVICE_URL_ATTRIBUTE, "http://127.0.0.1:8082/").setAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, "http://url").setFrontchannelLogout(true).update());
    SamlClientBuilder builder = new SamlClientBuilder();
    CreateArtifactMessageStepBuilder camb = new CreateArtifactMessageStepBuilder(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, REDIRECT, builder);
    ArtifactResolutionService ars = new ArtifactResolutionService("http://127.0.0.1:8082/");
    Thread arsThread = new Thread(ars);
    try {
        arsThread.start();
        synchronized (ars) {
            ars.wait();
            SAMLDocumentHolder samlResponse = builder.authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, REDIRECT).setProtocolBinding(JBossSAMLURIConstants.SAML_HTTP_REDIRECT_BINDING.getUri()).build().login().user(bburkeUser).build().processSamlResponse(REDIRECT).transformObject(x -> {
                SAML2Object samlObj = extractNameIdAndSessionIndexAndTerminate(x);
                setArtifactResolutionServiceLogoutRequest(ars);
                return samlObj;
            }).build().artifactMessage(camb).build().getSamlResponse(REDIRECT);
            assertThat(samlResponse.getSamlObject(), instanceOf(StatusResponseType.class));
            StatusResponseType srt = (StatusResponseType) samlResponse.getSamlObject();
            assertThat(srt, isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
            assertThat(camb.getLastArtifact(), is(ars.getLastArtifactResolve().getArtifact()));
        }
    } finally {
        ars.stop();
        arsThread.join();
    }
}
Also used : SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) ArtifactResolutionService(org.keycloak.testsuite.util.ArtifactResolutionService) CreateArtifactMessageStepBuilder(org.keycloak.testsuite.util.saml.CreateArtifactMessageStepBuilder) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Test(org.junit.Test)

Example 53 with SAMLDocumentHolder

use of org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder in project keycloak by keycloak.

the class SAMLParserTest method testSaml20EncryptedAssertionWithNewlines.

@Test
public void testSaml20EncryptedAssertionWithNewlines() throws Exception {
    SAMLDocumentHolder holder = assertParsed("KEYCLOAK-4489-encrypted-assertion-with-newlines.xml", SAMLDocumentHolder.class);
    assertThat(holder.getSamlObject(), instanceOf(ResponseType.class));
    ResponseType resp = (ResponseType) holder.getSamlObject();
    assertThat(resp.getAssertions().size(), is(1));
    ResponseType.RTChoiceType rtChoiceType = resp.getAssertions().get(0);
    assertNull(rtChoiceType.getAssertion());
    assertNotNull(rtChoiceType.getEncryptedAssertion());
    PrivateKey privateKey = DerUtils.decodePrivateKey(Base64.decode(PRIVATE_KEY));
    AssertionUtil.decryptAssertion(holder, resp, privateKey);
    rtChoiceType = resp.getAssertions().get(0);
    assertNotNull(rtChoiceType.getAssertion());
    assertNull(rtChoiceType.getEncryptedAssertion());
}
Also used : SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) PrivateKey(java.security.PrivateKey) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Test(org.junit.Test)

Example 54 with SAMLDocumentHolder

use of org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder in project keycloak by keycloak.

the class SamlClient method extractSamlResponseFromRedirect.

/**
 * Extracts and parses value of SAMLResponse query parameter from the given URI.
 * If the realmPublicKey parameter is passed the response signature is
 * validated.
 *
 * @param responseUri The redirect URI to use
 * @param realmPublicKey The public realm key for validating signature in REDIRECT query parameters
 * @return
 */
public static SAMLDocumentHolder extractSamlResponseFromRedirect(String responseUri, String realmPublicKey) throws IOException {
    MultivaluedMap<String, String> encodedParams = parseEncodedQueryParameters(URI.create(responseUri).getRawQuery());
    String samlResponse = encodedParams.getFirst(GeneralConstants.SAML_RESPONSE_KEY);
    String samlRequest = encodedParams.getFirst(GeneralConstants.SAML_REQUEST_KEY);
    assertTrue("Only one SAMLRequest/SAMLResponse check", (samlResponse != null && samlRequest == null) || (samlResponse == null && samlRequest != null));
    String samlDoc = RedirectBindingUtil.urlDecode(samlResponse != null ? samlResponse : samlRequest);
    SAMLDocumentHolder documentHolder = SAMLRequestParser.parseResponseRedirectBinding(samlDoc);
    if (realmPublicKey != null) {
        // if the public key is passed verify the signature of the redirect URI
        try {
            KeyLocator locator = new KeyLocator() {

                @Override
                public Key getKey(String kid) throws KeyManagementException {
                    return org.keycloak.testsuite.util.KeyUtils.publicKeyFromString(realmPublicKey);
                }

                @Override
                public void refreshKeyCache() {
                }
            };
            SamlProtocolUtils.verifyRedirectSignature(documentHolder, locator, encodedParams, samlResponse != null ? GeneralConstants.SAML_RESPONSE_KEY : GeneralConstants.SAML_REQUEST_KEY);
        } catch (VerificationException e) {
            throw new IOException(e);
        }
    }
    return documentHolder;
}
Also used : KeyLocator(org.keycloak.rotation.KeyLocator) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) VerificationException(org.keycloak.common.VerificationException) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException)

Example 55 with SAMLDocumentHolder

use of org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder in project keycloak by keycloak.

the class ArtifactResolutionService method invoke.

/**
 * This is the method called when a message is received by the endpoint.
 * It gets the message, extracts the ArtifactResolve message from the SOAP, creates a SOAP message containing
 * an ArtifactResponse message with the configured SAML message, and returns it.
 * @param msg The SOAP message received by the endpoint, in Source format
 * @return A StreamSource containing the ArtifactResponse
 */
@Override
public Source invoke(Source msg) {
    byte[] response;
    try (StringWriter w = new StringWriter()) {
        Transformer trans = TransformerFactory.newInstance().newTransformer();
        trans.transform(msg, new StreamResult(w));
        String s = w.toString();
        Document doc = Soap.extractSoapMessage(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)));
        SAMLDocumentHolder samlDoc = SAML2Request.getSAML2ObjectFromDocument(doc);
        if (samlDoc.getSamlObject() instanceof ArtifactResolveType) {
            lastArtifactResolve = (ArtifactResolveType) samlDoc.getSamlObject();
        } else {
            lastArtifactResolve = null;
        }
        Document artifactResponse = SamlProtocolUtils.convert(artifactResponseType);
        response = Soap.createMessage().addToBody(artifactResponse).getBytes();
    } catch (ProcessingException | ConfigurationException | TransformerException | ParsingException | IOException e) {
        throw new RuntimeException(e);
    }
    return new StreamSource(new ByteArrayInputStream(response));
}
Also used : ArtifactResolveType(org.keycloak.dom.saml.v2.protocol.ArtifactResolveType) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) StreamSource(javax.xml.transform.stream.StreamSource) IOException(java.io.IOException) Document(org.w3c.dom.Document) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) StringWriter(java.io.StringWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) ParsingException(org.keycloak.saml.common.exceptions.ParsingException) TransformerException(javax.xml.transform.TransformerException) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException)

Aggregations

SAMLDocumentHolder (org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder)83 Test (org.junit.Test)70 SamlClientBuilder (org.keycloak.testsuite.util.SamlClientBuilder)62 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)35 StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)29 Document (org.w3c.dom.Document)20 IOException (java.io.IOException)19 JBossSAMLURIConstants (org.keycloak.saml.common.constants.JBossSAMLURIConstants)18 ArtifactResponseType (org.keycloak.dom.saml.v2.protocol.ArtifactResponseType)17 AuthnRequestType (org.keycloak.dom.saml.v2.protocol.AuthnRequestType)14 URI (java.net.URI)12 List (java.util.List)12 Response (javax.ws.rs.core.Response)12 Matchers.containsString (org.hamcrest.Matchers.containsString)12 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)12 Matchers (org.keycloak.testsuite.util.Matchers)12 SamlClient (org.keycloak.testsuite.util.SamlClient)12 Matchers.is (org.hamcrest.Matchers.is)11 Assert.assertThat (org.junit.Assert.assertThat)11 Matchers.notNullValue (org.hamcrest.Matchers.notNullValue)10