Search in sources :

Example 46 with AssertionType

use of org.keycloak.dom.saml.v2.assertion.AssertionType in project keycloak by keycloak.

the class SAMLAssertionWriter method write.

/**
 * Write an {@code AssertionType} to stream
 *
 * @param assertion
 *
 * @throws org.keycloak.saml.common.exceptions.ProcessingException
 */
public void write(AssertionType assertion) throws ProcessingException {
    StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.ASSERTION.get(), ASSERTION_NSURI.get());
    StaxUtil.writeNameSpace(writer, ASSERTION_PREFIX, ASSERTION_NSURI.get());
    StaxUtil.writeDefaultNameSpace(writer, ASSERTION_NSURI.get());
    // Attributes
    StaxUtil.writeAttribute(writer, JBossSAMLConstants.ID.get(), assertion.getID());
    StaxUtil.writeAttribute(writer, JBossSAMLConstants.VERSION.get(), assertion.getVersion());
    StaxUtil.writeAttribute(writer, JBossSAMLConstants.ISSUE_INSTANT.get(), assertion.getIssueInstant().toString());
    NameIDType issuer = assertion.getIssuer();
    if (issuer != null)
        write(issuer, new QName(ASSERTION_NSURI.get(), JBossSAMLConstants.ISSUER.get(), ASSERTION_PREFIX));
    SubjectType subject = assertion.getSubject();
    if (subject != null) {
        write(subject);
    }
    ConditionsType conditions = assertion.getConditions();
    if (conditions != null) {
        StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.CONDITIONS.get(), ASSERTION_NSURI.get());
        if (conditions.getNotBefore() != null) {
            StaxUtil.writeAttribute(writer, JBossSAMLConstants.NOT_BEFORE.get(), conditions.getNotBefore().toString());
        }
        if (conditions.getNotOnOrAfter() != null) {
            StaxUtil.writeAttribute(writer, JBossSAMLConstants.NOT_ON_OR_AFTER.get(), conditions.getNotOnOrAfter().toString());
        }
        List<ConditionAbstractType> typeOfConditions = conditions.getConditions();
        if (typeOfConditions != null) {
            for (ConditionAbstractType typeCondition : typeOfConditions) {
                if (typeCondition instanceof AudienceRestrictionType) {
                    AudienceRestrictionType art = (AudienceRestrictionType) typeCondition;
                    StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.AUDIENCE_RESTRICTION.get(), ASSERTION_NSURI.get());
                    List<URI> audiences = art.getAudience();
                    if (audiences != null) {
                        for (URI audience : audiences) {
                            StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.AUDIENCE.get(), ASSERTION_NSURI.get());
                            StaxUtil.writeCharacters(writer, audience.toString());
                            StaxUtil.writeEndElement(writer);
                        }
                    }
                    StaxUtil.writeEndElement(writer);
                }
                if (typeCondition instanceof OneTimeUseType) {
                    StaxUtil.writeStartElement(writer, ASSERTION_PREFIX, JBossSAMLConstants.ONE_TIME_USE.get(), ASSERTION_NSURI.get());
                    StaxUtil.writeEndElement(writer);
                }
            }
        }
        StaxUtil.writeEndElement(writer);
    }
    AdviceType advice = assertion.getAdvice();
    if (advice != null)
        throw logger.notImplementedYet("Advice");
    Set<StatementAbstractType> statements = assertion.getStatements();
    if (statements != null) {
        for (StatementAbstractType statement : statements) {
            if (statement instanceof AuthnStatementType) {
                write((AuthnStatementType) statement, false);
            } else if (statement instanceof AttributeStatementType) {
                write((AttributeStatementType) statement);
            } else
                throw logger.writerUnknownTypeError(statement.getClass().getName());
        }
    }
    StaxUtil.writeEndElement(writer);
    StaxUtil.flush(writer);
}
Also used : QName(javax.xml.namespace.QName) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) URI(java.net.URI) ASSERTION_NSURI(org.keycloak.saml.common.constants.JBossSAMLURIConstants.ASSERTION_NSURI) OneTimeUseType(org.keycloak.dom.saml.v2.assertion.OneTimeUseType) AuthnStatementType(org.keycloak.dom.saml.v2.assertion.AuthnStatementType) ConditionAbstractType(org.keycloak.dom.saml.v2.assertion.ConditionAbstractType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) AdviceType(org.keycloak.dom.saml.v2.assertion.AdviceType) ConditionsType(org.keycloak.dom.saml.v2.assertion.ConditionsType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType)

Example 47 with AssertionType

use of org.keycloak.dom.saml.v2.assertion.AssertionType in project keycloak by keycloak.

the class SAMLParserTest method testEmptyAttributeValue.

@Test
public void testEmptyAttributeValue() throws Exception {
    ResponseType resp = assertParsed("KEYCLOAK-4790-Empty-attribute-value.xml", ResponseType.class);
    assertThat(resp.getAssertions(), hasSize(1));
    final AssertionType a = resp.getAssertions().get(0).getAssertion();
    assertThat(a, notNullValue());
    assertThat(a.getAttributeStatements(), hasSize(1));
    final List<ASTChoiceType> attributes = a.getAttributeStatements().iterator().next().getAttributes();
    assertThat(attributes, hasSize(3));
    assertThat(attributes, everyItem(notNullValue(ASTChoiceType.class)));
    final AttributeType attr0 = attributes.get(0).getAttribute();
    final AttributeType attr1 = attributes.get(1).getAttribute();
    final AttributeType attr2 = attributes.get(2).getAttribute();
    assertThat(attr0.getName(), is("urn:oid:0.9.2342.19200300.100.1.2"));
    assertThat(attr0.getAttributeValue(), hasSize(1));
    assertThat(attr0.getAttributeValue().get(0), instanceOf(String.class));
    assertThat((String) attr0.getAttributeValue().get(0), is(""));
    assertThat(attr1.getName(), is("urn:oid:0.9.2342.19200300.100.1.3"));
    assertThat(attr1.getAttributeValue(), hasSize(1));
    assertThat(attr1.getAttributeValue().get(0), instanceOf(String.class));
    assertThat((String) attr1.getAttributeValue().get(0), is("aa"));
    assertThat(attr2.getName(), is("urn:oid:0.9.2342.19200300.100.1.4"));
    assertThat(attr2.getAttributeValue(), hasSize(1));
    assertThat(attr2.getAttributeValue().get(0), instanceOf(String.class));
    assertThat((String) attr2.getAttributeValue().get(0), is(""));
}
Also used : RequestedAttributeType(org.keycloak.dom.saml.v2.metadata.RequestedAttributeType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) EncryptedAssertionType(org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Matchers.containsString(org.hamcrest.Matchers.containsString) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) StatusResponseType(org.keycloak.dom.saml.v2.protocol.StatusResponseType) Test(org.junit.Test)

Example 48 with AssertionType

use of org.keycloak.dom.saml.v2.assertion.AssertionType in project keycloak by keycloak.

the class SAMLParserTest method testSaml20AssertionsAnyTypeAttributeValue.

@Test
public void testSaml20AssertionsAnyTypeAttributeValue() throws Exception {
    AssertionType assertion = assertParsed("saml20-assertion-anytype-attribute-value.xml", AssertionType.class);
    AttributeStatementType attributeStatementType = assertion.getAttributeStatements().iterator().next();
    assertThat(attributeStatementType.getAttributes(), hasSize(5));
    for (AttributeStatementType.ASTChoiceType choiceType : attributeStatementType.getAttributes()) {
        AttributeType attr = choiceType.getAttribute();
        String attrName = attr.getName();
        Object value = attr.getAttributeValue().get(0);
        // test selected attributes
        switch(attrName) {
            case "attr:type:string":
                assertThat(value, is((Object) "CITIZEN"));
                break;
            case "attr:notype:string":
                assertThat(value, instanceOf(String.class));
                assertThat(value, is((Object) "CITIZEN"));
                break;
            case "attr:notype:element":
                assertThat(value, instanceOf(String.class));
                assertThat((String) value, containsString("hospitaal x"));
                value = attr.getAttributeValue().get(1);
                assertThat(value, instanceOf(String.class));
                assertThat((String) value, containsString("hopital x"));
                break;
            case "founded":
                assertThat(value, is((Object) XMLTimeUtil.parse("2002-05-30T09:30:10-06:00")));
                break;
            case "expanded":
                assertThat(value, is((Object) XMLTimeUtil.parse("2002-06-30")));
                break;
            default:
                break;
        }
    }
}
Also used : ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) RequestedAttributeType(org.keycloak.dom.saml.v2.metadata.RequestedAttributeType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) EncryptedAssertionType(org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Matchers.containsString(org.hamcrest.Matchers.containsString) Test(org.junit.Test)

Example 49 with AssertionType

use of org.keycloak.dom.saml.v2.assertion.AssertionType in project keycloak by keycloak.

the class SAMLAssertionFactory method createAssertion.

/**
 * <p>
 * Creates a SAMLV2 {@code AssertionType} with the specified values.
 * </p>
 *
 * @param id a {@code String} representing the assertion ID.
 * @param issuerID a {@code NameIDType} that identifies the assertion issuer.
 * @param issueInstant the assertion time of creation.
 * @param conditions the {@code ConditionsType} that specify the conditions under which the assertion is to be
 * considered
 * valid
 * @param subject the {@code SubjectType} that identifies the authenticated principal.
 * @param statements a list of statements associated with the authenticated principal.
 *
 * @return
 */
public static AssertionType createAssertion(String id, NameIDType issuerID, XMLGregorianCalendar issueInstant, ConditionsType conditions, SubjectType subject, List<StatementAbstractType> statements) {
    AssertionType assertion = new AssertionType(id, issueInstant);
    assertion.setIssuer(issuerID);
    if (conditions != null)
        assertion.setConditions(conditions);
    if (subject != null)
        assertion.setSubject(subject);
    if (statements != null) {
        for (StatementAbstractType statement : statements) {
            assertion.addStatement(statement);
        }
    }
    return assertion;
}
Also used : AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType)

Example 50 with AssertionType

use of org.keycloak.dom.saml.v2.assertion.AssertionType 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)

Aggregations

AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)43 Test (org.junit.Test)24 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)21 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)20 EncryptedAssertionType (org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType)15 AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)13 AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)13 Element (org.w3c.dom.Element)12 List (java.util.List)11 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)11 AuthnStatementType (org.keycloak.dom.saml.v2.assertion.AuthnStatementType)10 Document (org.w3c.dom.Document)10 AudienceRestrictionType (org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType)9 ConditionsType (org.keycloak.dom.saml.v2.assertion.ConditionsType)9 SubjectType (org.keycloak.dom.saml.v2.assertion.SubjectType)9 StatementAbstractType (org.keycloak.dom.saml.v2.assertion.StatementAbstractType)8 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)8 HashMap (java.util.HashMap)7 StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)7 SAML2Object (org.keycloak.dom.saml.v2.SAML2Object)6