org.keycloak.saml.common.constants.JBossSAMLURIConstants Java Examples

The following examples show how to use org.keycloak.saml.common.constants.JBossSAMLURIConstants. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseSAML2BindingBuilder.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void signAssertion(Document samlDocument) throws ProcessingException {
    Element originalAssertionElement = org.keycloak.saml.common.util.DocumentUtil.getChildElement(samlDocument.getDocumentElement(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    if (originalAssertionElement == null) return;
    Node clonedAssertionElement = originalAssertionElement.cloneNode(true);
    Document temporaryDocument;

    try {
        temporaryDocument = org.keycloak.saml.common.util.DocumentUtil.createDocument();
    } catch (ConfigurationException e) {
        throw new ProcessingException(e);
    }

    temporaryDocument.adoptNode(clonedAssertionElement);
    temporaryDocument.appendChild(clonedAssertionElement);

    signDocument(temporaryDocument);

    samlDocument.adoptNode(clonedAssertionElement);

    Element parentNode = (Element) originalAssertionElement.getParentNode();

    parentNode.replaceChild(clonedAssertionElement, originalAssertionElement);
}
 
Example #2
Source File: RoleMapperTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void testExpectedRoles(String clientId, String... expectedRoles) {
    SAMLDocumentHolder document = new SamlClientBuilder()
      .authnRequest(getAuthServerSamlEndpoint(REALM_NAME), clientId, SAML_ASSERTION_CONSUMER_URL_EMPLOYEE_2, Binding.POST).build()
      .login().user(bburkeUser).build()
      .getSamlResponse(Binding.POST);

    assertThat(document.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));

    Stream<AssertionType> assertions = assertionsUnencrypted(document.getSamlObject());
    Stream<AttributeType> attributes = attributesUnecrypted(attributeStatements(assertions));
    Set<String> roles = attributes
      .filter(a -> a.getName().equals(ROLE_ATTRIBUTE_NAME))
      .flatMap(a -> a.getAttributeValue().stream())
      .map(Object::toString)
      .collect(Collectors.toSet());

    assertThat(roles, containsInAnyOrder(expectedRoles));
}
 
Example #3
Source File: IdpInitiatedLoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdpInitiatedLoginPostAdminUrl() throws IOException {
    String url = adminClient.realm(REALM_NAME).clients().findByClientId(SAML_CLIENT_ID_SALES_POST).get(0)
            .getAttributes().get(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE);
    try (Closeable c = ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST)
            .setAdminUrl(url)
            .setAttribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, null)
            .setAttribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_REDIRECT_ATTRIBUTE, null)
            .update()) {
        new SamlClientBuilder()
                .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build()
                .login().user(bburkeUser).build()
                .processSamlResponse(Binding.POST)
                .transformObject(ob -> {
                    assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
                    ResponseType resp = (ResponseType) ob;
                    assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST));
                    return null;
                })
                .build()
                .execute();
    }
}
 
Example #4
Source File: IdpInitiatedLoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdpInitiatedLoginPost() {
    new SamlClientBuilder()
      .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build()
      .login().user(bburkeUser).build()
      .processSamlResponse(Binding.POST)
        .transformObject(ob -> {
          assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
          ResponseType resp = (ResponseType) ob;
          assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST));
          return null;
        })
        .build()
      .execute()
    ;
}
 
Example #5
Source File: IdpInitiatedLoginTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdpInitiatedLoginRedirect() throws IOException {
    String url = adminClient.realm(REALM_NAME).clients().findByClientId(SAML_CLIENT_ID_SALES_POST).get(0)
            .getAttributes().get(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE);
    try (Closeable c = ClientAttributeUpdater.forClient(adminClient, REALM_NAME, SAML_CLIENT_ID_SALES_POST)
            .setAttribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_POST_ATTRIBUTE, null)
            .setAttribute(SamlProtocol.SAML_ASSERTION_CONSUMER_URL_REDIRECT_ATTRIBUTE, url)
            .update()) {
        new SamlClientBuilder()
                .idpInitiatedLogin(getAuthServerSamlEndpoint(REALM_NAME), "sales-post").build()
                .login().user(bburkeUser).build()
                .processSamlResponse(Binding.REDIRECT)
                .transformObject(ob -> {
                    assertThat(ob, Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
                    ResponseType resp = (ResponseType) ob;
                    assertThat(resp.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST));
                    return null;
                })
                .build()
                .execute();
    }
}
 
Example #6
Source File: SamlRedirectBindingTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueryParametersInSamlProcessingUriRedirectWithSignature() throws Exception {
    SamlClient samlClient = new SamlClientBuilder()
            .authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST_SIG,
                    SAML_ASSERTION_CONSUMER_URL_SALES_POST_SIG + "?param1=value1&param2=value2",
                    Binding.REDIRECT)
            .signWith(SAML_CLIENT_SALES_POST_SIG_PRIVATE_KEY, SAML_CLIENT_SALES_POST_SIG_PUBLIC_KEY)
            .build()
            .login().user(bburkeUser).build().doNotFollowRedirects()
            .execute(hr -> {
                try {
                    // obtain the document validating the signature (it should be valid)
                    SAMLDocumentHolder doc = Binding.REDIRECT.extractResponse(hr, REALM_PUBLIC_KEY);
                    // assert doc is OK and the destination really has the extra parameters
                    assertThat(doc.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
                    assertThat(doc.getSamlObject(), instanceOf(ResponseType.class));
                    ResponseType res = (ResponseType) doc.getSamlObject();
                    assertThat(res.getDestination(), is(SAML_ASSERTION_CONSUMER_URL_SALES_POST_SIG + "?param1=value1&param2=value2"));
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
            });
}
 
Example #7
Source File: SAML11ParserUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Parse Attribute value
 *
 * @param xmlEventReader
 *
 * @return
 *
 * @throws ParsingException
 */
public static Object parseAttributeValue(XMLEventReader xmlEventReader) throws ParsingException {
    StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
    StaxParserUtil.validate(startElement, JBossSAMLConstants.ATTRIBUTE_VALUE.get());

    Attribute type = startElement.getAttributeByName(new QName(JBossSAMLURIConstants.XSI_NSURI.get(), "type", "xsi"));
    if (type == null) {
        return StaxParserUtil.getElementText(xmlEventReader);
    }

    String typeValue = StaxParserUtil.getAttributeValue(type);
    if (typeValue.contains(":string")) {
        return StaxParserUtil.getElementText(xmlEventReader);
    }

    throw logger.parserUnknownXSI(typeValue);
}
 
Example #8
Source File: SamlProtocol.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected String getNameId(String nameIdFormat, CommonClientSessionModel clientSession, UserSessionModel userSession) {
    if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.get())) {
        final String email = userSession.getUser().getEmail();
        if (email == null) {
            logger.debugf("E-mail of the user %s has to be set for %s NameIDFormat", userSession.getUser().getUsername(), JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.get());
        }
        return email;
    } else if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_TRANSIENT.get())) {
        // "G-" stands for "generated" Add this for the slight possibility of collisions.
        return "G-" + UUID.randomUUID().toString();
    } else if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_PERSISTENT.get())) {
        return getPersistentNameId(clientSession, userSession);
    } else if (nameIdFormat.equals(JBossSAMLURIConstants.NAMEID_FORMAT_UNSPECIFIED.get())) {
        // TODO: Support for persistent NameID (pseudo-random identifier persisted in user object)
        return userSession.getUser().getUsername();
    } else {
        return userSession.getUser().getUsername();
    }
}
 
Example #9
Source File: BaseSAML2BindingBuilder.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void encryptDocument(Document samlDocument) throws ProcessingException {
    String samlNSPrefix = getSAMLNSPrefix(samlDocument);

    try {
        QName encryptedAssertionElementQName = new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(),
                JBossSAMLConstants.ENCRYPTED_ASSERTION.get(), samlNSPrefix);

        byte[] secret = RandomSecret.createRandomSecret(encryptionKeySize / 8);
        SecretKey secretKey = new SecretKeySpec(secret, encryptionAlgorithm);

        // encrypt the Assertion element and replace it with a EncryptedAssertion element.
        XMLEncryptionUtil.encryptElement(new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(),
                        JBossSAMLConstants.ASSERTION.get(), samlNSPrefix), samlDocument, encryptionPublicKey,
                secretKey, encryptionKeySize, encryptedAssertionElementQName, true);
    } catch (Exception e) {
        throw new ProcessingException("failed to encrypt", e);
    }

}
 
Example #10
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testFrontchannelLogoutInSameBrowser() {
    adminClient.realm(REALM_NAME)
      .clients().get(sales2Rep.getId())
      .update(ClientBuilder.edit(sales2Rep)
        .frontchannelLogout(true)
        .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, "")
        .build());

    SAMLDocumentHolder samlResponse = prepareLogIntoTwoApps()
      .logoutRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, POST)
        .nameId(nameIdRef::get)
        .sessionIndex(sessionIndexRef::get)
        .build()

      .getSamlResponse(POST);

    assertThat(samlResponse.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    assertLogoutEvent(SAML_CLIENT_ID_SALES_POST);
}
 
Example #11
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testFrontchannelLogoutNoLogoutServiceUrlSetInSameBrowser() {
    adminClient.realm(REALM_NAME)
      .clients().get(sales2Rep.getId())
      .update(ClientBuilder.edit(sales2Rep)
        .frontchannelLogout(true)
        .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, "")
        .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE, "")
        .build());

    SAMLDocumentHolder samlResponse = prepareLogIntoTwoApps()
      .logoutRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, POST)
        .nameId(nameIdRef::get)
        .sessionIndex(sessionIndexRef::get)
        .build()

      .getSamlResponse(POST);

    assertThat(samlResponse.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
 
Example #12
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testFrontchannelLogoutDifferentBrowser() {
    adminClient.realm(REALM_NAME)
      .clients().get(sales2Rep.getId())
      .update(ClientBuilder.edit(sales2Rep)
        .frontchannelLogout(true)
        .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, "")
        .build());

    SAMLDocumentHolder samlResponse = prepareLogIntoTwoApps()
      .clearCookies()

      .logoutRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, POST)
        .nameId(nameIdRef::get)
        .sessionIndex(sessionIndexRef::get)
        .build()

      .getSamlResponse(POST);

    assertThat(samlResponse.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
 
Example #13
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private SAML2Object createAuthnResponse(SAML2Object so) {
    AuthnRequestType req = (AuthnRequestType) so;
    try {
        final ResponseType res = new SAML2LoginResponseBuilder()
          .requestID(req.getID())
          .destination(req.getAssertionConsumerServiceURL().toString())
          .issuer(BROKER_SERVICE_ID)
          .assertionExpiration(1000000)
          .subjectExpiration(1000000)
          .requestIssuer(getAuthServerRealmBase(REALM_NAME).toString())
          .nameIdentifier(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.get(), "[email protected]")
          .authMethod(JBossSAMLURIConstants.AC_UNSPECIFIED.get())
          .sessionIndex("idp:" + UUID.randomUUID())
          .buildModel();

        NameIDType nameId = (NameIDType) res.getAssertions().get(0).getAssertion().getSubject().getSubType().getBaseID();
        nameId.setNameQualifier(NAME_QUALIFIER);
        nameId.setSPNameQualifier(SP_NAME_QUALIFIER);
        nameId.setSPProvidedID(SP_PROVIDED_ID);

        return res;
    } catch (ConfigurationException | ProcessingException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #14
Source File: LogoutTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogoutDifferentBrowser() {
    // This is in fact the same as admin logging out a session from admin console.
    // This always succeeds as it is essentially the same as backend logout which
    // does not report errors to client but only to the server log
    adminClient.realm(REALM_NAME)
      .clients().get(sales2Rep.getId())
      .update(ClientBuilder.edit(sales2Rep)
        .frontchannelLogout(false)
        .attribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_POST_ATTRIBUTE, "")
      .removeAttribute(SamlProtocol.SAML_SINGLE_LOGOUT_SERVICE_URL_REDIRECT_ATTRIBUTE)
        .build());

    SAMLDocumentHolder samlResponse = prepareLogIntoTwoApps()
      .clearCookies()

      .logoutRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, POST)
        .nameId(nameIdRef::get)
        .sessionIndex(sessionIndexRef::get)
        .build()

      .getSamlResponse(POST);

    assertThat(samlResponse.getSamlObject(), isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
 
Example #15
Source File: TokenEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected Response buildAuthenticatedResponse(AuthenticatedClientSessionModel clientSession, String redirectUri,
                                              Document samlDocument, JaxrsSAML2BindingBuilder bindingBuilder)
        throws ConfigurationException, ProcessingException, IOException {
    JaxrsSAML2BindingBuilder.PostBindingBuilder builder = bindingBuilder.postBinding(samlDocument);

    Element assertionElement;
    if (samlClient.requiresEncryption()) {
        assertionElement = DocumentUtil.getElement(builder.getDocument(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ENCRYPTED_ASSERTION.get()));
    } else {
        assertionElement = DocumentUtil.getElement(builder.getDocument(), new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ASSERTION.get()));
    }
    if (assertionElement == null) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    String assertion = DocumentUtil.getNodeAsString(assertionElement);
    return Response.ok(assertion, MediaType.APPLICATION_XML_TYPE).build();
}
 
Example #16
Source File: AudienceProtocolMappersTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void testExpectedAudiences(String... audiences) {
    SAMLDocumentHolder document = new SamlClientBuilder()
      .authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_EMPLOYEE_2, SAML_ASSERTION_CONSUMER_URL_EMPLOYEE_2, SamlClient.Binding.POST).build()
      .login().user(bburkeUser).build()
      .getSamlResponse(SamlClient.Binding.POST);

    Assert.assertNotNull(document.getSamlObject());
    Assert.assertThat(document.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions());
    Assert.assertThat(((ResponseType) document.getSamlObject()).getAssertions().size(), greaterThan(0));
    Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0));
    Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0).getAssertion());
    AudienceRestrictionType audience = ((ResponseType) document.getSamlObject())
            .getAssertions().get(0).getAssertion().getConditions().getConditions()
            .stream()
            .filter(AudienceRestrictionType.class::isInstance)
            .map(AudienceRestrictionType.class::cast)
            .findFirst().orElse(null);
    Assert.assertNotNull(audience);
    Assert.assertNotNull(audience.getAudience());
    List<String> values = audience.getAudience().stream().map(uri -> uri.toString()).collect(Collectors.toList());
    Assert.assertThat(values, containsInAnyOrder(audiences));
}
 
Example #17
Source File: LogoutHelperTest.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@Test
public void testLogoutRequest() throws Exception {
    HttpEntity requestEntity = LogoutHelper.buildSingleLogoutRequest("ST-test");
    Document doc = DocumentUtil.getDocument(requestEntity.getContent());

    assertEquals("LogoutRequest", doc.getDocumentElement().getLocalName());
    assertEquals(JBossSAMLURIConstants.PROTOCOL_NSURI.get(), doc.getDocumentElement().getNamespaceURI());
    assertEquals("2.0", doc.getDocumentElement().getAttribute("Version"));
    assertFalse(doc.getDocumentElement().getAttribute("ID").isEmpty());
    assertFalse(doc.getDocumentElement().getAttribute("IssueInstant").isEmpty());

    Node nameID = doc.getDocumentElement().getElementsByTagNameNS(JBossSAMLURIConstants.ASSERTION_NSURI.get(), "NameID").item(0);
    assertFalse(nameID.getTextContent() == null || nameID.getTextContent().isEmpty());

    Node sessionIndex = doc.getDocumentElement().getElementsByTagNameNS(JBossSAMLURIConstants.PROTOCOL_NSURI.get(), "SessionIndex").item(0);
    assertEquals("ST-test", sessionIndex.getTextContent());
}
 
Example #18
Source File: SAMLResponseWriter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void write(ArtifactResponseType response) throws ProcessingException {
    StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.ARTIFACT_RESPONSE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get());

    StaxUtil.writeNameSpace(writer, PROTOCOL_PREFIX, JBossSAMLURIConstants.PROTOCOL_NSURI.get());
    StaxUtil.writeNameSpace(writer, ASSERTION_PREFIX, JBossSAMLURIConstants.ASSERTION_NSURI.get());
    StaxUtil.writeDefaultNameSpace(writer, JBossSAMLURIConstants.ASSERTION_NSURI.get());

    writeBaseAttributes(response);

    NameIDType issuer = response.getIssuer();
    if (issuer != null) {
        write(issuer, new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ISSUER.get(), ASSERTION_PREFIX));
    }

    Element sig = response.getSignature();
    if (sig != null) {
        StaxUtil.writeDOMElement(writer, sig);
    }
    ExtensionsType extensions = response.getExtensions();
    if (extensions != null && extensions.getAny() != null && ! extensions.getAny().isEmpty()) {
        write(extensions);
    }

    StatusType status = response.getStatus();
    if (status != null) {
        write(status);
    }
    Object anyObj = response.getAny();
    if (anyObj instanceof AuthnRequestType) {
        AuthnRequestType authn = (AuthnRequestType) anyObj;
        SAMLRequestWriter requestWriter = new SAMLRequestWriter(writer);
        requestWriter.write(authn);
    } else if (anyObj instanceof ResponseType) {
        ResponseType rt = (ResponseType) anyObj;
        write(rt);
    }

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example #19
Source File: KcSamlSignedBrokerTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginUserAllNamespacesInTopElement() {
    AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, getConsumerRoot() + "/sales-post/saml", null);

    Document doc;
    try {
        doc = extractNamespacesToTopLevelElement(SAML2Request.convert(loginRep));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }

    SAMLDocumentHolder samlResponse = new SamlClientBuilder()
      .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, Binding.POST).build()   // Request to consumer IdP
      .login().idp(bc.getIDPAlias()).build()

      .processSamlResponse(Binding.POST)    // AuthnRequest to producer IdP
        .targetAttributeSamlRequest()
        .transformDocument(this::extractNamespacesToTopLevelElement)
        .build()

      .login().user(bc.getUserLogin(), bc.getUserPassword()).build()

      .processSamlResponse(Binding.POST)    // Response from producer IdP
        .transformDocument(this::extractNamespacesToTopLevelElement)
        .build()

      // first-broker flow
      .updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build()
      .followOneRedirect()

      .getSamlResponse(Binding.POST);       // Response from consumer IdP

    Assert.assertThat(samlResponse, Matchers.notNullValue());
    Assert.assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
}
 
Example #20
Source File: SAMLMetadataWriter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void writeAttributeAuthorityDescriptor(AttributeAuthorityDescriptorType attributeAuthority)
        throws ProcessingException {
    StaxUtil.writeStartElement(writer, METADATA_PREFIX, JBossSAMLConstants.ATTRIBUTE_AUTHORITY_DESCRIPTOR.get(),
            JBossSAMLURIConstants.METADATA_NSURI.get());

    writeProtocolSupportEnumeration(attributeAuthority.getProtocolSupportEnumeration());

    Element signature = attributeAuthority.getSignature();
    if (signature != null) {
        StaxUtil.writeDOMElement(writer, signature);
    }
    ExtensionsType extensions = attributeAuthority.getExtensions();
    if (extensions != null) {
        StaxUtil.writeDOMElement(writer, extensions.getElement());
    }

    List<KeyDescriptorType> keyDescriptorList = attributeAuthority.getKeyDescriptor();
    for (KeyDescriptorType keyDescriptor : keyDescriptorList) {
        writeKeyDescriptor(keyDescriptor);
    }

    List<EndpointType> attributeServices = attributeAuthority.getAttributeService();
    for (EndpointType endpoint : attributeServices) {
        writeAttributeService(endpoint);
    }

    List<String> nameIDFormats = attributeAuthority.getNameIDFormat();
    for (String nameIDFormat : nameIDFormats) {
        writeNameIDFormat(nameIDFormat);
    }

    List<AttributeType> attributes = attributeAuthority.getAttribute();
    for (AttributeType attributeType : attributes) {
        write(attributeType);
    }
    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example #21
Source File: SAMLMetadataWriter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void writeAttributeService(EndpointType endpoint) throws ProcessingException {
    StaxUtil.writeStartElement(writer, METADATA_PREFIX, JBossSAMLConstants.ATTRIBUTE_SERVICE.get(), JBossSAMLURIConstants.METADATA_NSURI.get());

    writeEndpointType(endpoint);

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example #22
Source File: SAMLParserTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaml20AssertionContents() throws Exception {
    AssertionType a = assertParsed("saml20-assertion-example.xml", AssertionType.class);

    assertThat(a.getSubject().getConfirmation(), hasSize(1));
    assertThat(a.getSubject().getConfirmation().get(0).getSubjectConfirmationData(), notNullValue());
    assertThat(a.getSubject().getConfirmation().get(0).getSubjectConfirmationData().getAnyType(), instanceOf(KeyInfoType.class));

    KeyInfoType kit = (KeyInfoType) a.getSubject().getConfirmation().get(0).getSubjectConfirmationData().getAnyType();
    assertThat(kit.getContent(), hasItem(instanceOf(RSAKeyValueType.class)));
    RSAKeyValueType rsaKit = (RSAKeyValueType) kit.getContent().get(0);
    assertThat(rsaKit.getModulus(), notNullValue());
    assertThat(rsaKit.getExponent(), notNullValue());

    assertThat(a.getStatements(), containsInAnyOrder(instanceOf(AuthnStatementType.class), instanceOf(AttributeStatementType.class)));
    for (StatementAbstractType statement : a.getStatements()) {
        if (statement instanceof AuthnStatementType) {
            AuthnStatementType as = (AuthnStatementType) statement;
            assertThat(as.getSessionNotOnOrAfter(), notNullValue());
            assertThat(as.getSessionNotOnOrAfter(), is(XMLTimeUtil.parse("2009-06-17T18:55:10.738Z")));

            final AuthnContextType ac = as.getAuthnContext();
            assertThat(ac, notNullValue());
            assertThat(ac.getSequence(), notNullValue());

            assertThat(ac.getSequence().getClassRef().getValue(), is(JBossSAMLURIConstants.AC_UNSPECIFIED.getUri()));

            assertThat(ac.getSequence(), notNullValue());
            assertThat(ac.getSequence().getAuthnContextDecl(), nullValue());
        }
    }
}
 
Example #23
Source File: FixedHostnameTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void assertSamlLogin(Keycloak testAdminClient, String realm, String expectedBaseUrl) throws Exception {
    final String realmUrl = expectedBaseUrl + "/auth/realms/" + realm;
    final String baseSamlEndpointUrl = realmUrl + "/protocol/saml";
    String entityDescriptor = null;
    RealmResource realmResource = testAdminClient.realm(realm);
    ClientRepresentation clientRep = ClientBuilder.create()
      .protocol(SamlProtocol.LOGIN_PROTOCOL)
      .clientId(SAML_CLIENT_ID)
      .enabled(true)
      .attribute(SamlConfigAttributes.SAML_CLIENT_SIGNATURE_ATTRIBUTE, "false")
      .redirectUris("http://foo.bar/")
      .build();
    try (Creator<ClientResource> c = Creator.create(realmResource, clientRep);
      Creator<UserResource> u = Creator.create(realmResource, UserBuilder.create().username("bicycle").password("race").enabled(true).build())) {
        SAMLDocumentHolder samlResponse = new SamlClientBuilder()
          .authnRequest(new URI(baseSamlEndpointUrl), SAML_CLIENT_ID, "http://foo.bar/", Binding.POST).build()
          .login().user("bicycle", "race").build()
          .getSamlResponse(Binding.POST);

        assertThat(samlResponse.getSamlObject(), org.keycloak.testsuite.util.Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
        ResponseType response = (ResponseType) samlResponse.getSamlObject();

        assertThat(response.getAssertions(), hasSize(1));
        assertThat(response.getAssertions().get(0).getAssertion().getIssuer().getValue(), is(realmUrl));
    } catch (Exception e) {
        log.errorf("Caught exception while parsing SAML descriptor %s", entityDescriptor);
    }
}
 
Example #24
Source File: KcSamlBrokerAllowedClockSkewTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void loginClientExpiredResponseFromIdPWithClockSkew() throws Exception {
    try (Closeable idpUpdater = new IdentityProviderAttributeUpdater(identityProviderResource)
            .setAttribute(SAMLIdentityProviderConfig.ALLOWED_CLOCK_SKEW, "60")
            .update()) {

        AuthnRequestType loginRep = SamlClient.createLoginRequestDocument(AbstractSamlTest.SAML_CLIENT_ID_SALES_POST, AbstractSamlTest.SAML_ASSERTION_CONSUMER_URL_SALES_POST, null);

        Document doc = SAML2Request.convert(loginRep);

        SAMLDocumentHolder samlResponse = new SamlClientBuilder()
          .authnRequest(getConsumerSamlEndpoint(bc.consumerRealmName()), doc, SamlClient.Binding.POST).build()   // Request to consumer IdP
          .login().idp(bc.getIDPAlias()).build()

          .processSamlResponse(SamlClient.Binding.POST)    // AuthnRequest to producer IdP
            .targetAttributeSamlRequest()
            .build()

          .login().user(bc.getUserLogin(), bc.getUserPassword()).build()

          .addStep(() -> KcSamlBrokerAllowedClockSkewTest.this.setTimeOffset(-30)) // offset to the past but inside the clock skew
          .processSamlResponse(SamlClient.Binding.POST)    // Response from producer IdP expired but valid with the clock skew
            .build()

          // first-broker flow
          .updateProfile().firstName("a").lastName("b").email(bc.getUserEmail()).username(bc.getUserLogin()).build()
          .followOneRedirect()

          .getSamlResponse(SamlClient.Binding.POST);       // Response from consumer IdP

        Assert.assertThat(samlResponse, Matchers.notNullValue());
        Assert.assertThat(samlResponse.getSamlObject(), isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    }
}
 
Example #25
Source File: KcSamlBrokerSessionNotOnOrAfterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Test
public void testConsumerIdpInitiatedLoginContainsSessionNotOnOrAfter() throws Exception {
    SAMLDocumentHolder samlResponse = new SamlClientBuilder()
            .idpInitiatedLogin(getConsumerSamlEndpoint(REALM_CONS_NAME), "sales-post").build()
            // Request login via kc-saml-idp
            .login().idp(IDP_SAML_ALIAS).build()

            .processSamlResponse(SamlClient.Binding.POST)    // AuthnRequest to producer IdP
                .targetAttributeSamlRequest()
                .build()

            // Login in provider realm
            .login().user(USER_LOGIN, USER_PASSWORD).build()

            // Send the response to the consumer realm
            .processSamlResponse(SamlClient.Binding.POST).build()

            // Create account in comsumer realm
            .updateProfile().username(USER_LOGIN).email(USER_EMAIL).firstName("Firstname").lastName("Lastname").build()
            .followOneRedirect()

            // Obtain the response sent to the app
            .getSamlResponse(SamlClient.Binding.POST);

    assertThat(samlResponse.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    ResponseType resp = (ResponseType) samlResponse.getSamlObject();
    Set<StatementAbstractType> statements = resp.getAssertions().get(0).getAssertion().getStatements();

    AuthnStatementType authType = statements.stream()
            .filter(statement -> statement instanceof AuthnStatementType)
            .map(s -> (AuthnStatementType) s)
            .findFirst().orElse(null);

    assertThat(authType, notNullValue());
    assertThat(authType.getSessionNotOnOrAfter(), notNullValue());
    assertThat(authType.getSessionNotOnOrAfter(), is(XMLTimeUtil.add(authType.getAuthnInstant(), adminClient.realm(REALM_CONS_NAME).toRepresentation().getSsoSessionMaxLifespan() * 1000)));
}
 
Example #26
Source File: CustomSamlProtocol.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private Element newSamlAttributeElement(Document samlDocument, String friendlyName, String name, String nameFormat, Object value, String type) {

        Element targetSamlAttributeElement = samlDocument.createElementNS(JBossSAMLURIConstants.ASSERTION_NSURI.get(), "Attribute");

        if (friendlyName != null) {
            targetSamlAttributeElement.setAttribute("FriendlyName", friendlyName);
        }
        targetSamlAttributeElement.setAttribute("Name", name);
        if (nameFormat != null) {
            targetSamlAttributeElement.setAttribute("NameFormat", nameFormat);
        }

        Element samlAttributeValue = samlDocument.createElementNS(JBossSAMLURIConstants.ASSERTION_NSURI.get(), "AttributeValue");
        samlAttributeValue.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        samlAttributeValue.setAttribute("xsi:type", type);
        targetSamlAttributeElement.appendChild(samlAttributeValue);

        if (value instanceof String) {
            samlAttributeValue.setTextContent((String) value);
        } else if (value instanceof Element) {
            samlAttributeValue.appendChild((Element) value);
        } else if (value != null) {
            samlAttributeValue.setTextContent(value.toString());
        } else {
            samlAttributeValue.setTextContent(String.valueOf(value));
        }

        return targetSamlAttributeElement;
    }
 
Example #27
Source File: SAMLMetadataWriter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void writeEntitiesDescriptor(EntitiesDescriptorType entities) throws ProcessingException {
    StaxUtil.writeStartElement(writer, METADATA_PREFIX, JBossSAMLConstants.ENTITIES_DESCRIPTOR.get(), JBossSAMLURIConstants.METADATA_NSURI.get());

    StaxUtil.writeDefaultNameSpace(writer, JBossSAMLURIConstants.METADATA_NSURI.get());
    StaxUtil.writeNameSpace(writer, "md", JBossSAMLURIConstants.METADATA_NSURI.get());
    StaxUtil.writeNameSpace(writer, "saml", JBossSAMLURIConstants.ASSERTION_NSURI.get());
    StaxUtil.writeNameSpace(writer, "ds", JBossSAMLURIConstants.XMLDSIG_NSURI.get());

    if (entities.getValidUntil() != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.VALID_UNTIL.get(), entities.getValidUntil().toString());
    }
    if (entities.getID() != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.ID.get(), entities.getID());
    }

    if (entities.getName() != null) {
        StaxUtil.writeAttribute(writer, JBossSAMLConstants.NAME.get(), entities.getName());
    }

    Element signature = entities.getSignature();
    if (signature != null) {
        StaxUtil.writeDOMElement(writer, signature);
    }
    ExtensionsType extensions = entities.getExtensions();
    if (extensions != null) {
        StaxUtil.writeDOMElement(writer, extensions.getElement());
    }

    List<Object> entityDescriptors = entities.getEntityDescriptor();
    for (Object ed : entityDescriptors) {
        if (ed instanceof EntityDescriptorType) {
            writeEntityDescriptor((EntityDescriptorType) ed);
        } else
            writeEntitiesDescriptor((EntitiesDescriptorType) ed);
    }

    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
 
Example #28
Source File: SamlService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected String getBindingType(AuthnRequestType requestAbstractType) {
    URI requestedProtocolBinding = requestAbstractType.getProtocolBinding();

    if (requestedProtocolBinding != null) {
        if (JBossSAMLURIConstants.SAML_HTTP_POST_BINDING.get().equals(requestedProtocolBinding.toString())) {
            return SamlProtocol.SAML_POST_BINDING;
        } else {
            return SamlProtocol.SAML_REDIRECT_BINDING;
        }
    }

    return getBindingType();
}
 
Example #29
Source File: SAMLLogoutAdapterTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void assertSamlLogoutResponse(CloseableHttpResponse response) {
    try {
        assertThat(POST.extractResponse(response).getSamlObject(), Matchers.isSamlStatusResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #30
Source File: SAMLMetadataUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get the {@link X509Certificate} from the KeyInfo
 *
 * @param keyDescriptor
 *
 * @return
 *
 * @throws org.keycloak.saml.common.exceptions.ProcessingException
 * @throws org.keycloak.saml.common.exceptions.ConfigurationException
 */
public static X509Certificate getCertificate(KeyDescriptorType keyDescriptor) throws ConfigurationException,
        ProcessingException {
    X509Certificate cert = null;
    Element keyInfo = keyDescriptor.getKeyInfo();
    if (keyInfo != null) {
        NodeList x509DataNodes = keyInfo.getElementsByTagName("X509Data");
        if (x509DataNodes == null || x509DataNodes.getLength() == 0) {
            x509DataNodes = keyInfo.getElementsByTagNameNS(JBossSAMLURIConstants.XMLDSIG_NSURI.get(), "X509Data");
        }

        if (x509DataNodes == null || x509DataNodes.getLength() == 0) {
            x509DataNodes = keyInfo.getElementsByTagName("ds:X509Data");
        }

        if (x509DataNodes != null && x509DataNodes.getLength() > 0) {
            // Choose the first one
            Node x509DataNode = x509DataNodes.item(0);
            NodeList children = x509DataNode.getChildNodes();
            int len = children != null ? children.getLength() : 0;
            for (int i = 0; i < len; i++) {
                Node nl = children.item(i);
                if (nl.getNodeName().contains("X509Certificate")) {
                    Node certNode = nl.getFirstChild();
                    String certNodeValue = certNode.getNodeValue();
                    cert = XMLSignatureUtil.getX509CertificateFromKeyInfoString(certNodeValue.replaceAll("\\s", ""));
                    break;
                }
            }
        }
    }
    return cert;
}