use of org.keycloak.scripting.ScriptingProvider 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);
}
}
Aggregations