Search in sources :

Example 51 with ResponseType

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

the class SAMLServletAdapterTest method testInvalidCredentialsEcpFlow.

@Test
public void testInvalidCredentialsEcpFlow() throws Exception {
    Response authnRequestResponse = AdminClientUtil.createResteasyClient().target(ecpSPPage.toString()).request().header("Accept", "text/html; application/vnd.paos+xml").header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'").get();
    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));
    Iterator<javax.xml.soap.Node> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(new QName("urn:liberty:paos:2003-08", "Request"));
    it.next();
    it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    javax.xml.soap.Node ecpRequestHeader = it.next();
    NodeList idpList = ((SOAPHeaderElement) ecpRequestHeader).getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "IDPList");
    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));
    NodeList idpEntries = idpList.item(0).getChildNodes();
    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));
    String singleSignOnService = null;
    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");
        singleSignOnService = location.getNodeValue();
    }
    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());
    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "baspassword";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());
    Response authenticationResponse = AdminClientUtil.createResteasyClient().target(singleSignOnService).request().header(HttpHeaders.AUTHORIZATION, authHeader).post(Entity.entity(DocumentUtil.asString(authenticationRequest), "application/soap+xml"));
    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));
    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));
    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();
    Assert.assertThat(samlResponse, notNullValue());
    StatusResponseType responseType = (StatusResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();
    Assert.assertThat(statusCode.getStatusCode().getValue().toString(), is(not(JBossSAMLURIConstants.STATUS_SUCCESS.get())));
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) NamedNodeMap(org.w3c.dom.NamedNodeMap) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) StatusCodeType(org.keycloak.dom.saml.v2.protocol.StatusCodeType) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 52 with ResponseType

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

the class SAMLLoginResponseHandlingTest method testNilAttributeValueAttribute.

@Test
public void testNilAttributeValueAttribute() {
    beginAuthenticationAndLogin(employee2ServletPage, SamlClient.Binding.POST).processSamlResponse(// Update response with Nil attribute
    SamlClient.Binding.POST).transformObject(ob -> {
        assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
        ResponseType resp = (ResponseType) ob;
        Set<StatementAbstractType> statements = resp.getAssertions().get(0).getAssertion().getStatements();
        AttributeStatementType attributeType = (AttributeStatementType) statements.stream().filter(statement -> statement instanceof AttributeStatementType).findFirst().orElse(new AttributeStatementType());
        AttributeType attr = new AttributeType("attribute-with-null-attribute-value");
        attr.addAttributeValue(null);
        attributeType.addAttribute(new AttributeStatementType.ASTChoiceType(attr));
        resp.getAssertions().get(0).getAssertion().addStatement(attributeType);
        return ob;
    }).build().navigateTo(employee2ServletPage.getUriBuilder().clone().path("getAttributes").build()).execute(response -> {
        Assert.assertThat(response, statusCodeIsHC(Response.Status.OK));
        Assert.assertThat(response, bodyHC(containsString("attribute-with-null-attribute-value: <br />")));
    });
}
Also used : AttributeStatementHelper(org.keycloak.protocol.saml.mappers.AttributeStatementHelper) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) WaitUtils.waitUntilElement(org.keycloak.testsuite.util.WaitUtils.waitUntilElement) RoleListMapper(org.keycloak.protocol.saml.mappers.RoleListMapper) Matchers.statusCodeIsHC(org.keycloak.testsuite.util.Matchers.statusCodeIsHC) X500SAMLProfileConstants(org.keycloak.saml.processing.core.saml.v2.constants.X500SAMLProfileConstants) HashMap(java.util.HashMap) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) Matchers.bodyHC(org.keycloak.testsuite.util.Matchers.bodyHC) AdapterActionsFilter(org.keycloak.testsuite.adapter.filter.AdapterActionsFilter) Page(org.jboss.arquillian.graphene.page.Page) REALM_PUBLIC_KEY(org.keycloak.testsuite.saml.AbstractSamlTest.REALM_PUBLIC_KEY) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) REALM_PRIVATE_KEY(org.keycloak.testsuite.saml.AbstractSamlTest.REALM_PRIVATE_KEY) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) LinkedHashMap(java.util.LinkedHashMap) Assert.assertThat(org.junit.Assert.assertThat) EmployeeSigServlet(org.keycloak.testsuite.adapter.page.EmployeeSigServlet) Document(org.w3c.dom.Document) Map(java.util.Map) SamlClient(org.keycloak.testsuite.util.SamlClient) ContainerConstants(org.keycloak.testsuite.utils.arquillian.ContainerConstants) URI(java.net.URI) ClientResource(org.keycloak.admin.client.resource.ClientResource) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) WaitUtils(org.keycloak.testsuite.util.WaitUtils) WebArchive(org.jboss.shrinkwrap.api.spec.WebArchive) ProtocolMappersResource(org.keycloak.admin.client.resource.ProtocolMappersResource) Matchers(org.keycloak.testsuite.util.Matchers) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) By(org.openqa.selenium.By) Set(java.util.Set) Test(org.junit.Test) Employee2Servlet(org.keycloak.testsuite.adapter.page.Employee2Servlet) WaitUtils.waitForPageToLoad(org.keycloak.testsuite.util.WaitUtils.waitForPageToLoad) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) URLAssert.assertCurrentUrlStartsWith(org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith) Response(javax.ws.rs.core.Response) Deployment(org.jboss.arquillian.container.test.api.Deployment) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType) AppServerContainer(org.keycloak.testsuite.arquillian.annotation.AppServerContainer) ApiUtil.getCreatedId(org.keycloak.testsuite.admin.ApiUtil.getCreatedId) Assert(org.junit.Assert) PublicKeyLocator(org.keycloak.adapters.rotation.PublicKeyLocator) Matchers.containsString(org.hamcrest.Matchers.containsString) UIUtils.getRawPageSource(org.keycloak.testsuite.util.UIUtils.getRawPageSource) SAML2ErrorResponseBuilder(org.keycloak.saml.SAML2ErrorResponseBuilder) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) Set(java.util.Set) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 53 with ResponseType

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

the class SAMLServletAdapterTest method testSuccessfulEcpFlow.

@Test
public void testSuccessfulEcpFlow() throws Exception {
    Response authnRequestResponse = AdminClientUtil.createResteasyClient().target(ecpSPPage.toString()).request().header("Accept", "text/html; application/vnd.paos+xml").header("PAOS", "ver='urn:liberty:paos:2003-08' ;'urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp'").get();
    SOAPMessage authnRequestMessage = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(authnRequestResponse.readEntity(byte[].class)));
    // printDocument(authnRequestMessage.getSOAPPart().getContent(), System.out);
    Iterator<javax.xml.soap.Node> it = authnRequestMessage.getSOAPHeader().<SOAPHeaderElement>getChildElements(new QName("urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp", "Request"));
    SOAPHeaderElement ecpRequestHeader = (SOAPHeaderElement) it.next();
    NodeList idpList = ecpRequestHeader.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:protocol", "IDPList");
    Assert.assertThat("No IDPList returned from Service Provider", idpList.getLength(), is(1));
    NodeList idpEntries = idpList.item(0).getChildNodes();
    Assert.assertThat("No IDPEntry returned from Service Provider", idpEntries.getLength(), is(1));
    String singleSignOnService = null;
    for (int i = 0; i < idpEntries.getLength(); i++) {
        Node item = idpEntries.item(i);
        NamedNodeMap attributes = item.getAttributes();
        Node location = attributes.getNamedItem("Loc");
        singleSignOnService = location.getNodeValue();
    }
    Assert.assertThat("Could not obtain SSO Service URL", singleSignOnService, notNullValue());
    Document authenticationRequest = authnRequestMessage.getSOAPBody().getFirstChild().getOwnerDocument();
    String username = "pedroigor";
    String password = "password";
    String pair = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBytes(pair.getBytes());
    Response authenticationResponse = AdminClientUtil.createResteasyClient().target(singleSignOnService).request().header(HttpHeaders.AUTHORIZATION, authHeader).post(Entity.entity(DocumentUtil.asString(authenticationRequest), "text/xml"));
    Assert.assertThat(authenticationResponse.getStatus(), is(OK.getStatusCode()));
    SOAPMessage responseMessage = MessageFactory.newInstance().createMessage(null, new ByteArrayInputStream(authenticationResponse.readEntity(byte[].class)));
    // printDocument(responseMessage.getSOAPPart().getContent(), System.out);
    SOAPHeader responseMessageHeaders = responseMessage.getSOAPHeader();
    NodeList ecpResponse = responseMessageHeaders.getElementsByTagNameNS(JBossSAMLURIConstants.ECP_PROFILE.get(), JBossSAMLConstants.RESPONSE__ECP.get());
    Assert.assertThat("No ECP Response", ecpResponse.getLength(), is(1));
    Node samlResponse = responseMessage.getSOAPBody().getFirstChild();
    Assert.assertThat(samlResponse, notNullValue());
    ResponseType responseType = (ResponseType) SAMLParser.getInstance().parse(samlResponse);
    StatusCodeType statusCode = responseType.getStatus().getStatusCode();
    Assert.assertThat(statusCode.getValue().toString(), is(JBossSAMLURIConstants.STATUS_SUCCESS.get()));
    Assert.assertThat(responseType.getDestination(), is(ecpSPPage.toString()));
    Assert.assertThat(responseType.getSignature(), notNullValue());
    Assert.assertThat(responseType.getAssertions().size(), is(1));
    SOAPMessage samlResponseRequest = MessageFactory.newInstance().createMessage();
    samlResponseRequest.getSOAPBody().addDocument(responseMessage.getSOAPBody().extractContentAsDocument());
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    samlResponseRequest.writeTo(os);
    Response serviceProviderFinalResponse = AdminClientUtil.createResteasyClient().target(responseType.getDestination()).request().post(Entity.entity(os.toByteArray(), "application/vnd.paos+xml"));
    Map<String, NewCookie> cookies = serviceProviderFinalResponse.getCookies();
    Invocation.Builder resourceRequest = AdminClientUtil.createResteasyClient().target(responseType.getDestination()).request();
    for (NewCookie cookie : cookies.values()) {
        resourceRequest.cookie(cookie);
    }
    Response resourceResponse = resourceRequest.get();
    Assert.assertThat(resourceResponse.readEntity(String.class), containsString("pedroigor"));
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) NamedNodeMap(org.w3c.dom.NamedNodeMap) Invocation(javax.ws.rs.client.Invocation) QName(javax.xml.namespace.QName) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Response(javax.ws.rs.core.Response) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) StatusCodeType(org.keycloak.dom.saml.v2.protocol.StatusCodeType) SOAPHeader(javax.xml.soap.SOAPHeader) NewCookie(javax.ws.rs.core.NewCookie) AbstractSamlTest(org.keycloak.testsuite.saml.AbstractSamlTest) Test(org.junit.Test)

Example 54 with ResponseType

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

the class SAMLDataMarshallerTest method testParseResponse.

@Test
public void testParseResponse() {
    SAMLDataMarshaller serializer = new SAMLDataMarshaller();
    ResponseType responseType = serializer.deserialize(TEST_RESPONSE, ResponseType.class);
    // test ResponseType
    Assert.assertEquals("ID_4804cf50-cd96-4b92-823e-89adaa0c78ba", responseType.getID());
    Assert.assertEquals("http://localhost:8081/auth/realms/realm-with-broker/broker/kc-saml-idp-basic/endpoint", responseType.getDestination());
    Assert.assertEquals("http://localhost:8082/auth/realms/realm-with-saml-idp-basic", responseType.getIssuer().getValue());
    Assert.assertEquals("ID_29b196c2-d641-45c8-a423-8ed8e54d4cf9", responseType.getAssertions().get(0).getID());
    // back to String
    String serialized = serializer.serialize(responseType);
    Assert.assertEquals(TEST_RESPONSE, serialized);
}
Also used : SAMLDataMarshaller(org.keycloak.broker.saml.SAMLDataMarshaller) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) Test(org.junit.Test)

Example 55 with ResponseType

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

the class SAMLDataMarshallerTest method testSerializeWithNamespaceNotInSignatureElement.

@Test
public void testSerializeWithNamespaceNotInSignatureElement() throws Exception {
    SAMLParser parser = SAMLParser.getInstance();
    try (InputStream st = SAMLDataMarshallerTest.class.getResourceAsStream("saml-response-ds-ns-above-signature.xml")) {
        Object parsedObject = parser.parse(st);
        assertThat(parsedObject, instanceOf(ResponseType.class));
        ResponseType response = (ResponseType) parsedObject;
        SAMLDataMarshaller serializer = new SAMLDataMarshaller();
        String serializedResponse = serializer.serialize(response);
        String serializedAssertion = serializer.serialize(response.getAssertions().get(0).getAssertion());
        ResponseType deserializedResponse = serializer.deserialize(serializedResponse, ResponseType.class);
        assertThat(deserializedResponse, CoreMatchers.notNullValue());
        assertThat(deserializedResponse.getID(), CoreMatchers.is("id-EYgqtumZ-P-Ph7t37f-brUKMwB5MKix0sNjr-0YV"));
        AssertionType deserializedAssertion = serializer.deserialize(serializedAssertion, AssertionType.class);
        assertThat(deserializedAssertion, CoreMatchers.notNullValue());
        assertThat(deserializedAssertion.getID(), CoreMatchers.is("id-4r-Xj702KQsM0gJyu3Fqpuwfe-LvDrEcQZpxKrhC"));
    }
}
Also used : InputStream(java.io.InputStream) SAMLParser(org.keycloak.saml.processing.core.parsers.saml.SAMLParser) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) SAMLDataMarshaller(org.keycloak.broker.saml.SAMLDataMarshaller) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) Test(org.junit.Test)

Aggregations

ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)75 Test (org.junit.Test)50 SamlClientBuilder (org.keycloak.testsuite.util.SamlClientBuilder)38 SAMLDocumentHolder (org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder)34 StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)33 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)26 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)25 JBossSAMLURIConstants (org.keycloak.saml.common.constants.JBossSAMLURIConstants)16 Document (org.w3c.dom.Document)15 URI (java.net.URI)13 List (java.util.List)12 Matchers.containsString (org.hamcrest.Matchers.containsString)12 Assert.assertThat (org.junit.Assert.assertThat)12 AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)12 AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)12 StatementAbstractType (org.keycloak.dom.saml.v2.assertion.StatementAbstractType)12 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)12 IOException (java.io.IOException)11 Response (javax.ws.rs.core.Response)11 Matchers (org.keycloak.testsuite.util.Matchers)11