Search in sources :

Example 21 with AttributeStatementType

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

the class ScriptBasedMapper method transformAttributeStatement.

/**
 *  This method attaches one or many attributes to the passed attribute statement.
 *  To obtain the attribute values, it executes the mapper's script and returns attaches the returned value to the
 *  attribute.
 *  If the returned attribute is an Array or is iterable, the mapper will either return multiple attributes, or an
 *  attribute with multiple values. The variant chosen depends on the configuration of the mapper
 *
 * @param attributeStatement The attribute statements to be added to a token
 * @param mappingModel The mapping model reflects the values that are actually input in the GUI
 * @param session The current session
 * @param userSession The current user session
 * @param clientSession The current client session
 */
@Override
public void transformAttributeStatement(AttributeStatementType attributeStatement, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
    UserModel user = userSession.getUser();
    String scriptSource = mappingModel.getConfig().get(ProviderConfigProperty.SCRIPT_TYPE);
    RealmModel realm = userSession.getRealm();
    String single = mappingModel.getConfig().get(SINGLE_VALUE_ATTRIBUTE);
    boolean singleAttribute = Boolean.parseBoolean(single);
    ScriptingProvider scripting = session.getProvider(ScriptingProvider.class);
    ScriptModel scriptModel = scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, "attribute-mapper-script_" + mappingModel.getName(), scriptSource, null);
    EvaluatableScriptAdapter script = scripting.prepareEvaluatableScript(scriptModel);
    Object attributeValue;
    try {
        attributeValue = script.eval((bindings) -> {
            bindings.put("user", user);
            bindings.put("realm", realm);
            bindings.put("clientSession", clientSession);
            bindings.put("userSession", userSession);
            bindings.put("keycloakSession", session);
        });
        // If the result is a an array or is iterable, get all values
        if (attributeValue.getClass().isArray()) {
            attributeValue = Arrays.asList((Object[]) attributeValue);
        }
        if (attributeValue instanceof Iterable) {
            if (singleAttribute) {
                AttributeType singleAttributeType = AttributeStatementHelper.createAttributeType(mappingModel);
                attributeStatement.addAttribute(new AttributeStatementType.ASTChoiceType(singleAttributeType));
                for (Object value : (Iterable) attributeValue) {
                    singleAttributeType.addAttributeValue(value);
                }
            } else {
                for (Object value : (Iterable) attributeValue) {
                    AttributeStatementHelper.addAttribute(attributeStatement, mappingModel, value.toString());
                }
            }
        } else {
            // single value case
            AttributeStatementHelper.addAttribute(attributeStatement, mappingModel, attributeValue.toString());
        }
    } catch (Exception ex) {
        LOGGER.error("Error during execution of ProtocolMapper script", ex);
        AttributeStatementHelper.addAttribute(attributeStatement, mappingModel, null);
    }
}
Also used : AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) EvaluatableScriptAdapter(org.keycloak.scripting.EvaluatableScriptAdapter) java.util(java.util) ProtocolMapperConfigException(org.keycloak.protocol.ProtocolMapperConfigException) ScriptingProvider(org.keycloak.scripting.ScriptingProvider) ScriptCompilationException(org.keycloak.scripting.ScriptCompilationException) Logger(org.jboss.logging.Logger) org.keycloak.models(org.keycloak.models) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) ProtocolMapperConfigException(org.keycloak.protocol.ProtocolMapperConfigException) ScriptCompilationException(org.keycloak.scripting.ScriptCompilationException) ScriptingProvider(org.keycloak.scripting.ScriptingProvider) AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) EvaluatableScriptAdapter(org.keycloak.scripting.EvaluatableScriptAdapter)

Example 22 with AttributeStatementType

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

the class XUATokenWriterTest method testXUAToken.

@Test
public void testXUAToken() throws ConfigurationException, ProcessingException {
    Document document = DocumentUtil.createDocument();
    AttributeType roleAttr = new AttributeType("urn:oasis:names:tc:xacml:2.0:subject:role");
    Element role = document.createElementNS("urn:hl7-org:v3", "Role");
    role.setAttributeNS("urn:hl7-org:v3", "code", "46255001");
    role.setAttributeNS("urn:hl7-org:v3", "codeSystem", "2.16.840.1.113883.6.96");
    role.setAttributeNS("urn:hl7-org:v3", "codeSystemName", "SNOMED_CT");
    role.setAttributeNS("urn:hl7-org:v3", "displayName", "Pharmacist");
    Attr attrCEType = document.createAttributeNS(JBossSAMLURIConstants.XSI_NSURI.get(), "type");
    attrCEType.setValue("CE");
    attrCEType.setPrefix("xsi");
    role.setAttributeNodeNS(attrCEType);
    roleAttr.addAttributeValue(role);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    SAMLAssertionWriter samlAssertionWriter = new SAMLAssertionWriter(StaxUtil.getXMLStreamWriter(byteArrayOutputStream));
    AttributeStatementType attributeStatementType = new AttributeStatementType();
    attributeStatementType.addAttribute(new AttributeStatementType.ASTChoiceType(roleAttr));
    samlAssertionWriter.write(attributeStatementType);
    String serializedAssertion = new String(byteArrayOutputStream.toByteArray(), GeneralConstants.SAML_CHARSET);
    Assert.assertEquals("<saml:AttributeStatement>" + "<saml:Attribute Name=\"urn:oasis:names:tc:xacml:2.0:subject:role\">" + "<saml:AttributeValue>" + "<Role xmlns=\"urn:hl7-org:v3\" code=\"46255001\" codeSystem=\"2.16.840.1.113883.6.96\" " + "codeSystemName=\"SNOMED_CT\" displayName=\"Pharmacist\" " + "xsi:type=\"CE\"></Role></saml:AttributeValue></saml:Attribute>" + "</saml:AttributeStatement>", serializedAssertion);
}
Also used : AttributeType(org.keycloak.dom.saml.v2.assertion.AttributeType) Element(org.w3c.dom.Element) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) Attr(org.w3c.dom.Attr) Test(org.junit.Test)

Example 23 with AttributeStatementType

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

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

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

Aggregations

AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)27 AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)25 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)12 ASTChoiceType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType.ASTChoiceType)11 Test (org.junit.Test)9 StatementAbstractType (org.keycloak.dom.saml.v2.assertion.StatementAbstractType)9 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)8 URI (java.net.URI)6 List (java.util.List)6 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)6 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 JBossSAMLURIConstants (org.keycloak.saml.common.constants.JBossSAMLURIConstants)5 ConfigurationException (org.keycloak.saml.common.exceptions.ConfigurationException)5 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)5 SamlClientBuilder (org.keycloak.testsuite.util.SamlClientBuilder)5 Set (java.util.Set)4 Collectors (java.util.stream.Collectors)4