Search in sources :

Example 26 with AssertionType

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

the class AdvancedAttributeToRoleMapper method applies.

protected boolean applies(final IdentityProviderMapperModel mapperModel, final BrokeredIdentityContext context) {
    Map<String, String> attributes = mapperModel.getConfigMap(ATTRIBUTE_PROPERTY_NAME);
    boolean areAttributeValuesRegexes = Boolean.parseBoolean(mapperModel.getConfig().get(ARE_ATTRIBUTE_VALUES_REGEX_PROPERTY_NAME));
    AssertionType assertion = (AssertionType) context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
    Set<AttributeStatementType> attributeAssertions = assertion.getAttributeStatements();
    if (attributeAssertions == null) {
        return false;
    }
    for (Map.Entry<String, String> attribute : attributes.entrySet()) {
        String attributeKey = attribute.getKey();
        List<Object> attributeValues = attributeAssertions.stream().flatMap(statements -> statements.getAttributes().stream()).filter(choiceType -> attributeKey.equals(choiceType.getAttribute().getName()) || attributeKey.equals(choiceType.getAttribute().getFriendlyName())).flatMap(choiceType -> choiceType.getAttribute().getAttributeValue().stream()).collect(Collectors.toList());
        boolean attributeValueMatch = areAttributeValuesRegexes ? valueMatchesRegex(attribute.getValue(), attributeValues) : attributeValues.contains(attribute.getValue());
        if (!attributeValueMatch) {
            return false;
        }
    }
    return true;
}
Also used : RegexUtils.valueMatchesRegex(org.keycloak.utils.RegexUtils.valueMatchesRegex) Arrays(java.util.Arrays) SAMLEndpoint(org.keycloak.broker.saml.SAMLEndpoint) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) IdentityProviderSyncMode(org.keycloak.models.IdentityProviderSyncMode) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) Set(java.util.Set) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) ConfigConstants(org.keycloak.broker.provider.ConfigConstants) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) HashSet(java.util.HashSet) List(java.util.List) SAMLIdentityProviderFactory(org.keycloak.broker.saml.SAMLIdentityProviderFactory) Map(java.util.Map) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Map(java.util.Map)

Example 27 with AssertionType

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

the class AttributeToRoleMapper method applies.

protected boolean applies(final IdentityProviderMapperModel mapperModel, final BrokeredIdentityContext context) {
    String name = mapperModel.getConfig().get(ATTRIBUTE_NAME);
    if (name != null && name.trim().equals(""))
        name = null;
    String friendly = mapperModel.getConfig().get(ATTRIBUTE_FRIENDLY_NAME);
    if (friendly != null && friendly.trim().equals(""))
        friendly = null;
    String desiredValue = Optional.ofNullable(mapperModel.getConfig().get(ATTRIBUTE_VALUE)).orElse("");
    AssertionType assertion = (AssertionType) context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
    for (AttributeStatementType statement : assertion.getAttributeStatements()) {
        for (AttributeStatementType.ASTChoiceType choice : statement.getAttributes()) {
            AttributeType attr = choice.getAttribute();
            if (name != null && !name.equals(attr.getName()))
                continue;
            if (friendly != null && !friendly.equals(attr.getFriendlyName()))
                continue;
            for (Object val : attr.getAttributeValue()) {
                val = Optional.ofNullable(val).orElse("");
                if (val.equals(desiredValue))
                    return true;
            }
        }
    }
    return false;
}
Also used : AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) RequestedAttributeType(org.keycloak.dom.saml.v2.metadata.RequestedAttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType)

Example 28 with AssertionType

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

the class UsernameTemplateMapper method setUserNameFromTemplate.

private void setUserNameFromTemplate(IdentityProviderMapperModel mapperModel, BrokeredIdentityContext context) {
    AssertionType assertion = (AssertionType) context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
    String template = mapperModel.getConfig().get(TEMPLATE);
    Matcher m = SUBSTITUTION.matcher(template);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String variable = m.group(1);
        UnaryOperator<String> transformer = Optional.ofNullable(m.group(2)).map(TRANSFORMERS::get).orElse(UnaryOperator.identity());
        if (variable.equals("ALIAS")) {
            m.appendReplacement(sb, transformer.apply(context.getIdpConfig().getAlias()));
        } else if (variable.equals("UUID")) {
            m.appendReplacement(sb, transformer.apply(KeycloakModelUtils.generateId()));
        } else if (variable.equals("NAMEID")) {
            SubjectType subject = assertion.getSubject();
            SubjectType.STSubType subType = subject.getSubType();
            NameIDType subjectNameID = (NameIDType) subType.getBaseID();
            m.appendReplacement(sb, transformer.apply(subjectNameID.getValue()));
        } else if (variable.startsWith("ATTRIBUTE.")) {
            String name = variable.substring("ATTRIBUTE.".length());
            String value = "";
            for (AttributeStatementType statement : assertion.getAttributeStatements()) {
                for (AttributeStatementType.ASTChoiceType choice : statement.getAttributes()) {
                    AttributeType attr = choice.getAttribute();
                    if (name.equals(attr.getName()) || name.equals(attr.getFriendlyName())) {
                        List<Object> attributeValue = attr.getAttributeValue();
                        if (attributeValue != null && !attributeValue.isEmpty()) {
                            value = attributeValue.get(0).toString();
                        }
                        break;
                    }
                }
            }
            m.appendReplacement(sb, transformer.apply(value));
        } else {
            m.appendReplacement(sb, m.group(1));
        }
    }
    m.appendTail(sb);
    Target t = getTarget(mapperModel.getConfig().get(TARGET));
    t.set(context, sb.toString());
}
Also used : Matcher(java.util.regex.Matcher) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) ArrayList(java.util.ArrayList) List(java.util.List) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType)

Example 29 with AssertionType

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

the class ProtocolMapperTest method hardcodedAttributeMapperWithNullValueTest.

@Test
public void hardcodedAttributeMapperWithNullValueTest() throws Exception {
    pmu.add(createSamlProtocolMapper(HardcodedAttributeMapper.PROVIDER_ID, AttributeStatementHelper.SAML_ATTRIBUTE_NAME, "HARDCODED_ATTRIBUTE", AttributeStatementHelper.SAML_ATTRIBUTE_NAMEFORMAT, AttributeStatementHelper.BASIC, HardcodedAttributeMapper.ATTRIBUTE_VALUE, null)).update();
    SAMLDocumentHolder samlResponse = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_EMPLOYEE_2, RoleMapperTest.SAML_ASSERTION_CONSUMER_URL_EMPLOYEE_2, SamlClient.Binding.POST).build().login().user(bburkeUser).build().getSamlResponse(SamlClient.Binding.POST);
    assertThat(samlResponse.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    Stream<AssertionType> assertions = assertionsUnencrypted(samlResponse.getSamlObject());
    Stream<AttributeType> attributes = attributesUnecrypted(attributeStatements(assertions));
    Set<Object> attributeValues = attributes.flatMap(a -> a.getAttributeValue().stream()).collect(Collectors.toSet());
    assertThat(attributeValues, hasSize(1));
    assertThat(attributeValues.iterator().next(), nullValue());
}
Also used : AttributeStatementHelper(org.keycloak.protocol.saml.mappers.AttributeStatementHelper) HardcodedAttributeMapper(org.keycloak.protocol.saml.mappers.HardcodedAttributeMapper) ClientAttributeUpdater(org.keycloak.testsuite.updaters.ClientAttributeUpdater) ProtocolMappersUpdater(org.keycloak.testsuite.updaters.ProtocolMappersUpdater) Matchers(org.keycloak.testsuite.util.Matchers) SamlStreams.attributesUnecrypted(org.keycloak.testsuite.util.SamlStreams.attributesUnecrypted) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) Set(java.util.Set) Test(org.junit.Test) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Collectors(java.util.stream.Collectors) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) Assert.assertThat(org.junit.Assert.assertThat) Stream(java.util.stream.Stream) RoleMapperTest.createSamlProtocolMapper(org.keycloak.testsuite.saml.RoleMapperTest.createSamlProtocolMapper) SamlClient(org.keycloak.testsuite.util.SamlClient) Matchers.hasSize(org.hamcrest.Matchers.hasSize) SamlStreams.attributeStatements(org.keycloak.testsuite.util.SamlStreams.attributeStatements) SamlStreams.assertionsUnencrypted(org.keycloak.testsuite.util.SamlStreams.assertionsUnencrypted) Collections(java.util.Collections) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Before(org.junit.Before) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Test(org.junit.Test)

Example 30 with AssertionType

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

the class BrokerTest method assertExpired.

private void assertExpired(XMLGregorianCalendar notBefore, XMLGregorianCalendar notOnOrAfter, boolean shouldPass) throws Exception {
    Status expectedStatus = shouldPass ? Status.OK : Status.BAD_REQUEST;
    final RealmResource realm = adminClient.realm(REALM_NAME);
    try (IdentityProviderCreator idp = new IdentityProviderCreator(realm, addIdentityProvider("https://saml.idp/"))) {
        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 -> {
            // always invent a new user identified by a different email address
            ResponseType rt = (ResponseType) resp;
            AssertionType a = rt.getAssertions().get(0).getAssertion();
            NameIDType nameId = new NameIDType();
            nameId.setFormat(URI.create(JBossSAMLURIConstants.NAMEID_FORMAT_EMAIL.get()));
            nameId.setValue(UUID.randomUUID() + "@random.email.org");
            SubjectType subject = new SubjectType();
            SubjectType.STSubType subType = new SubjectType.STSubType();
            subType.addBaseID(nameId);
            subject.setSubType(subType);
            a.setSubject(subject);
            ConditionsType conditions = a.getConditions();
            conditions.setNotBefore(notBefore);
            conditions.setNotOnOrAfter(notOnOrAfter);
            return rt;
        }).targetAttributeSamlResponse().targetUri(getSamlBrokerUrl(REALM_NAME)).build().assertResponse(org.keycloak.testsuite.util.Matchers.statusCodeIsHC(expectedStatus)).execute();
    }
}
Also used : Status(javax.ws.rs.core.Response.Status) 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) SubjectType(org.keycloak.dom.saml.v2.assertion.SubjectType) RealmResource(org.keycloak.admin.client.resource.RealmResource) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) IdentityProviderCreator(org.keycloak.testsuite.updaters.IdentityProviderCreator) ConditionsType(org.keycloak.dom.saml.v2.assertion.ConditionsType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType)

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