Search in sources :

Example 6 with ASTChoiceType

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

the class AssertionUtil method getRoles.

/**
 * Given an assertion, return the list of roles it may have
 *
 * @param assertion The {@link AssertionType}
 * @param roleKeys a list of string values representing the role keys. The list can be null.
 *
 * @return
 */
public static List<String> getRoles(AssertionType assertion, List<String> roleKeys) {
    List<String> roles = new ArrayList<>();
    Set<StatementAbstractType> statements = assertion.getStatements();
    for (StatementAbstractType statement : statements) {
        if (statement instanceof AttributeStatementType) {
            AttributeStatementType attributeStatement = (AttributeStatementType) statement;
            List<ASTChoiceType> attList = attributeStatement.getAttributes();
            for (ASTChoiceType obj : attList) {
                AttributeType attr = obj.getAttribute();
                if (roleKeys != null && roleKeys.size() > 0) {
                    if (!roleKeys.contains(attr.getName()))
                        continue;
                }
                List<Object> attributeValues = attr.getAttributeValue();
                if (attributeValues != null) {
                    for (Object attrValue : attributeValues) {
                        if (attrValue instanceof String) {
                            roles.add((String) attrValue);
                        } else if (attrValue instanceof Node) {
                            Node roleNode = (Node) attrValue;
                            roles.add(roleNode.getFirstChild().getNodeValue());
                        } else
                            throw logger.unknownObjectType(attrValue);
                    }
                }
            }
        }
    }
    return roles;
}
Also used : SAML11AttributeType(org.keycloak.dom.saml.v1.assertion.SAML11AttributeType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) SAML11AttributeStatementType(org.keycloak.dom.saml.v1.assertion.SAML11AttributeStatementType) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) SAML11StatementAbstractType(org.keycloak.dom.saml.v1.assertion.SAML11StatementAbstractType) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType)

Example 7 with ASTChoiceType

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

the class StatementUtil method createAttributeStatement.

/**
 * Create an attribute statement with all the attributes
 *
 * @param attributes a map with keys from {@link AttributeConstants}
 *
 * @return
 */
public static AttributeStatementType createAttributeStatement(Map<String, Object> attributes) {
    AttributeStatementType attrStatement = null;
    int i = 0;
    Set<String> keys = attributes.keySet();
    for (String key : keys) {
        if (i == 0) {
            // Deal with the X500 Profile of SAML2
            attrStatement = new AttributeStatementType();
            i++;
        }
        // if the attribute contains roles, add each role as an attribute.
        if (AttributeConstants.ROLES.equalsIgnoreCase(key)) {
            Object value = attributes.get(key);
            if (value instanceof Collection<?>) {
                Collection<?> roles = (Collection<?>) value;
                attrStatement = createAttributeStatement(new ArrayList(roles));
            }
        } else {
            AttributeType att;
            Object value = attributes.get(key);
            String uri = X500SAMLProfileConstants.getOID(key);
            if (StringUtil.isNotNull(uri)) {
                att = getX500Attribute(uri);
                att.setFriendlyName(key);
            } else {
                att = new AttributeType(key);
                att.setFriendlyName(key);
                att.setNameFormat(JBossSAMLURIConstants.ATTRIBUTE_FORMAT_URI.get());
            }
            if (Collection.class.isInstance(value)) {
                Collection collection = (Collection) value;
                Iterator iterator = collection.iterator();
                while (iterator.hasNext()) {
                    att.addAttributeValue(iterator.next());
                }
            } else if (String.class.isInstance(value)) {
                att.addAttributeValue(value);
            } else {
                throw new RuntimeException("Unsupported attribute value [" + value + "]. Values must be a string, even if using a Collection.");
            }
            attrStatement.addAttribute(new ASTChoiceType(att));
        }
    }
    return attrStatement;
}
Also used : AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) ArrayList(java.util.ArrayList) Iterator(java.util.Iterator) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) Collection(java.util.Collection)

Example 8 with ASTChoiceType

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

the class StatementUtil method asMap.

public static Map<String, Object> asMap(Set<AttributeStatementType> attributeStatementTypes) {
    Map<String, Object> attrMap = new HashMap<>();
    if (attributeStatementTypes != null && !attributeStatementTypes.isEmpty()) {
        attrMap = new HashMap<>();
        for (StatementAbstractType statement : attributeStatementTypes) {
            if (statement instanceof AttributeStatementType) {
                AttributeStatementType attrStat = (AttributeStatementType) statement;
                List<ASTChoiceType> attrs = attrStat.getAttributes();
                for (ASTChoiceType attrChoice : attrs) {
                    AttributeType attr = attrChoice.getAttribute();
                    String attributeName = attr.getFriendlyName();
                    if (attributeName == null) {
                        attributeName = attr.getName();
                    }
                    List<Object> values = attr.getAttributeValue();
                    if (values != null) {
                        if (values.size() == 1) {
                            attrMap.put(attributeName, values.get(0));
                        } else {
                            attrMap.put(attributeName, values);
                        }
                    }
                }
            }
        }
    }
    return attrMap;
}
Also used : HashMap(java.util.HashMap) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) StatementAbstractType(org.keycloak.dom.saml.v2.assertion.StatementAbstractType)

Example 9 with ASTChoiceType

use of org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType 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 10 with ASTChoiceType

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

the class BrokerTest method testNoNameIDAndPrincipalFromAttribute.

@Test
public void testNoNameIDAndPrincipalFromAttribute() throws IOException {
    final String userName = "newUser-" + UUID.randomUUID();
    final RealmResource realm = adminClient.realm(REALM_NAME);
    final IdentityProviderRepresentation rep = addIdentityProvider("https://saml.idp/");
    rep.getConfig().put(SAMLIdentityProviderConfig.NAME_ID_POLICY_FORMAT, "undefined");
    rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_TYPE, SamlPrincipalType.ATTRIBUTE.toString());
    rep.getConfig().put(SAMLIdentityProviderConfig.PRINCIPAL_ATTRIBUTE, "user");
    try (IdentityProviderCreator idp = new IdentityProviderCreator(realm, rep)) {
        new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, POST).build().login().idp(SAML_BROKER_ALIAS).build().processSamlResponse(REDIRECT).transformObject(this::createAuthnResponse).transformObject(resp -> {
            final ResponseType rt = (ResponseType) resp;
            final AssertionType assertion = rt.getAssertions().get(0).getAssertion();
            // Remove NameID from subject
            assertion.getSubject().setSubType(null);
            // Add attribute to get principal from
            AttributeStatementType attrStatement = new AttributeStatementType();
            AttributeType attribute = new AttributeType("user");
            attribute.addAttributeValue(userName);
            attrStatement.addAttribute(new ASTChoiceType(attribute));
            rt.getAssertions().get(0).getAssertion().addStatement(attrStatement);
            return rt;
        }).targetAttributeSamlResponse().targetUri(getSamlBrokerUrl(REALM_NAME)).build().followOneRedirect().updateProfile().username(userName).firstName("someFirstName").lastName("someLastName").email("some@email.com").build().followOneRedirect().assertResponse(org.keycloak.testsuite.util.Matchers.statusCodeIsHC(200)).execute();
    }
    final UserRepresentation userRepresentation = realm.users().search(userName).stream().findFirst().get();
    final List<UserSessionRepresentation> userSessions = realm.users().get(userRepresentation.getId()).getUserSessions();
    assertThat(userSessions, hasSize(1));
}
Also used : XMLTimeUtil(org.keycloak.saml.processing.core.saml.v2.util.XMLTimeUtil) KeyPair(java.security.KeyPair) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) POST(org.keycloak.testsuite.util.SamlClient.Binding.POST) Header(org.apache.http.Header) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) SAML2Object(org.keycloak.dom.saml.v2.SAML2Object) SAMLIdentityProviderConfig(org.keycloak.broker.saml.SAMLIdentityProviderConfig) SAMLIdentityProviderFactory(org.keycloak.broker.saml.SAMLIdentityProviderFactory) ClientsResource(org.keycloak.admin.client.resource.ClientsResource) ConditionsType(org.keycloak.dom.saml.v2.assertion.ConditionsType) Document(org.w3c.dom.Document) Requirement(org.keycloak.models.AuthenticationExecutionModel.Requirement) NameIDPolicyType(org.keycloak.dom.saml.v2.protocol.NameIDPolicyType) HasQName(org.keycloak.saml.processing.core.parsers.util.HasQName) URI(java.net.URI) HttpHeaders(org.apache.http.HttpHeaders) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) RealmResource(org.keycloak.admin.client.resource.RealmResource) IdentityProviderBuilder(org.keycloak.testsuite.util.IdentityProviderBuilder) UUID(java.util.UUID) Objects(java.util.Objects) List(java.util.List) Matchers.isSamlStatusResponse(org.keycloak.testsuite.util.Matchers.isSamlStatusResponse) Matchers.is(org.hamcrest.Matchers.is) SAML_CLIENT_ID_SALES_POST(org.keycloak.testsuite.saml.AbstractSamlTest.SAML_CLIENT_ID_SALES_POST) QName(javax.xml.namespace.QName) SamlPrincipalType(org.keycloak.protocol.saml.SamlPrincipalType) XmlDSigQNames(org.keycloak.saml.processing.core.parsers.saml.xmldsig.XmlDSigQNames) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) AtomicReference(java.util.concurrent.atomic.AtomicReference) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AuthenticationExecutionInfoRepresentation(org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation) RSA_SHA1(org.keycloak.saml.SignatureAlgorithm.RSA_SHA1) REDIRECT(org.keycloak.testsuite.util.SamlClient.Binding.REDIRECT) SAML2LoginResponseBuilder(org.keycloak.saml.SAML2LoginResponseBuilder) ProcessingException(org.keycloak.saml.common.exceptions.ProcessingException) DOMException(org.w3c.dom.DOMException) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) UserResource(org.keycloak.admin.client.resource.UserResource) Status(javax.ws.rs.core.Response.Status) ConfigurationException(org.keycloak.saml.common.exceptions.ConfigurationException) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) NodeList(org.w3c.dom.NodeList) AuthnRequestType(org.keycloak.dom.saml.v2.protocol.AuthnRequestType) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) REALM_NAME(org.keycloak.testsuite.saml.AbstractSamlTest.REALM_NAME) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) XMLGregorianCalendar(javax.xml.datatype.XMLGregorianCalendar) SAML_ASSERTION_CONSUMER_URL_SALES_POST(org.keycloak.testsuite.saml.AbstractSamlTest.SAML_ASSERTION_CONSUMER_URL_SALES_POST) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) IdentityProviderCreator(org.keycloak.testsuite.updaters.IdentityProviderCreator) IdpReviewProfileAuthenticatorFactory(org.keycloak.authentication.authenticators.broker.IdpReviewProfileAuthenticatorFactory) BaseSAML2BindingBuilder(org.keycloak.saml.BaseSAML2BindingBuilder) Element(org.w3c.dom.Element) Assert(org.junit.Assert) UserSessionRepresentation(org.keycloak.representations.idm.UserSessionRepresentation) RealmResource(org.keycloak.admin.client.resource.RealmResource) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) IdentityProviderCreator(org.keycloak.testsuite.updaters.IdentityProviderCreator) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) ASTChoiceType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType) UserRepresentation(org.keycloak.representations.idm.UserRepresentation) Test(org.junit.Test)

Aggregations

ASTChoiceType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType)10 AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)10 AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)8 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)3 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)2 StatementAbstractType (org.keycloak.dom.saml.v2.assertion.StatementAbstractType)2 IOException (java.io.IOException)1 URI (java.net.URI)1 KeyPair (java.security.KeyPair)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 List (java.util.List)1 Objects (java.util.Objects)1 UUID (java.util.UUID)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Status (javax.ws.rs.core.Response.Status)1 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)1