AM 7.3.0

Scripted decision node API

A Scripted Decision node calls server-side Groovy or JavaScript to set the outcome for the node programmatically and determine the path the authentication journey takes. The script can perform actions before setting the outcome.

To create and manage decision scripts, refer to Manage scripts (UI). Use the script type Decision node script for authentication trees.

A script can set the outcome directly, or use the Action interface:


Assign string values to the outcome variable.

  • JavaScript

if (expectedCondition) {
  outcome = "true"
} else {
  outcome = "false"

When configuring the Scripted Decision node, add the two outcomes true and false in Outcomes. Each outcome appears as a node endpoint that you connect to other nodes in the tree.

The outcome strings are not limited to true and false. Specify a value for each possible outcome and as many outcomes as required by the tree.


Use the Action interface to define the outcome or to perform an operation.

  • JavaScript

var fr = JavaImporter(

if (expectedCondition) {
  // Set outcome to "true", and set a custom session property:
  action = fr.Action.goTo("true").putSessionProperty("customKey", "customValue").build()
} else {
  // Set outcome to "false", and add an "errorMessage" in the shared node state:
  action = fr.Action.goTo("false").withErrorMessage("Friendly error description.").build()

An outcome specified with the Action.goTo method overrides the value set for the outcome variable:

  • JavaScript

action = Action.goTo("false").build() // Evaluation continues along the "false" outcome.
outcome = "true"                      // No effect.

A script can also use the Action interface to set session properties and callbacks. For details about the Action interface, refer to the Javadoc for Action.

Scripted decision node bindings

A script has access to AM bindings, objects that AM injects into the script execution context:

Binding Information


Add information to the AM audit logs.

Refer to Audit information.


Request additional data from the user using a callback.

Refer to Callbacks.


If the user has previously authenticated and has a session, use this variable to access the properties of that session.

This binding is only present when performing a session upgrade. Any properties added by nodes earlier in the tree only appear on the user’s new session when the journey completes; such properties are not available in the existingSession binding.


Make outbound HTTP calls.

For details, refer to the Javadoc for ChfHttpClient.


Access the data stored in the user’s profile.


Write a message to the AM debug log.

The name of the logger has the format: script-name (script-UUID); for example, myTestScript (36863ffb-40ec-48b9-94b1-9a99f71cc3b5).

For details, refer to the Javadoc for Debug.


Return the name of the realm to which the user is authenticating as a string.

For example, authenticating to the alpha realm returns a string value of /alpha.


Access the HTTP headers provided in the login request.


Access the HTTP request parameters provided in the login request.


Boolean—​True if evaluation has resumed after suspension; for example, after sending an email and receiving the response.


Access the secrets configured for AM in the environment.

For details, refer to the Javadoc for ScriptedSecrets.


Access data set by previous nodes in the tree, or store data to be used by subsequent nodes.

Access request header data

A script can access the headers in the login request with the methods of the requestHeaders object.

The script has access to a copy of the headers. Changing their values does not affect the request.


String[] requestHeaders.get(String headerName)

Returns an array of the values in the named request header, or null, if the property is not set.

Header names are case-sensitive.

  • JavaScript

if (requestHeaders.get("user-agent").get(0).indexOf("Chrome") !== -1) {
    outcome = "true"
} else {
    outcome = "false"

Access request parameter data

A script can access the query parameters in the login request with the methods of the requestParameters object.

The script has access to a copy of the parameters. Changing their values does not affect the request.


String[] requestParameters.get(String parameterName)

Return an array of the values in the named request parameter, or null, if the parameter is not available.

  • JavaScript

var service
var authIndexType = requestParameters.get("authIndexType")
if (authIndexType && String(authIndexType.get(0)) === "service") {
    service = requestParameters.get("authIndexValue").get(0)

if (service) {
    nodeState.putShared("service", service)

outcome = "true"

In JavaScript, the requestParameters values have a typeof of object.

Convert the values to strings before using strict equality comparisons.

Access shared state data

A script can access the shared state of the tree with the methods of the nodeState object. There are three types of state:


Non-sensitive state.


Sensitive state.

Transient state data is never sent back to the user’s browser in a callback so does not need to be encrypted.


Encrypted sensitive state.

Secure state data is sent back to the user’s browser encrypted as part of the shared state object.

Transient state data is promoted to secure state data when:

  • A callback to the user is about to occur.

  • A downstream node is detected in the journey, requesting data in the transient state as script input.

Unless the downstream node explicitly requests the secure state data by name, the authentication journey removes it from the node state after processing the next callback.

For example, a node in a registration journey stores a user’s password in transient state. The node sends a callback to the user before an inner tree node, downstream in the journey, consumes that password. As part of the callback, the journey assesses what to add to the secure state. It does this by checking the state inputs that downstream nodes in the journey require. Nodes that only request * are ignored, as this would result in putting everything that’s in transient state into secure state, and retaining sensitive information longer than necessary.

If a downstream node requires the password, it must therefore explicitly request it as state input, even if it lists the * wildcard as input.

AM stores shared state properties as name-value pairs. Property names are case-sensitive.


For additional methods and details, refer to the Javadoc for NodeState.

JsonValue nodeState.get(String propertyName)

Returns the value of the named property.

The value may come from the transient, secure, or shared states, in that order. If the same property is available in several states, the method returns the value of the property in the transient state first.

If the property is not set, the method returns null.

  • JavaScript

var currentAuthLevel = nodeState.get("authLevel")
var thePassword = nodeState.get("password")

outcome = "true"
NodeState nodeState.putShared(String propertyName, String propertyValue)

Sets the value of the named shared state property.

  • JavaScript

try {
  var thePassword = nodeState.get("password").asString()
} catch (e) {
  nodeState.putShared("errorMessage", e.toString())

outcome = "true"
NodeState nodeState.putTransient(String propertyName, String propertyValue)

Sets the value of the named transient state property.

  • JavaScript

nodeState.putTransient("sensitiveKey", "sensitiveValue")

outcome = "true"

Access profile data

A script can access profile data through the methods of the idRepository object.


Set idRepository.getAttribute(String userName, String attributeName)

Returns the values of the named attribute for the named user.

void idRepository.setAttribute(String userName, String attributeName, Array attributeValues)

Sets the named attribute as specified by the attribute value for the named user, and persists the result in the user’s profile.

  • JavaScript

var username = nodeState.get("username").asString()
idRepository.setAttribute(username, "mail", [""])

outcome = "true"
void idRepository.addAttribute(String userName, String attributeName, String attributeValue)

Add an attribute value to the list of attribute values associated with the attribute name for a particular user.

  • JavaScript

var username = nodeState.get("username").asString()
var attribute = "mail"

// Add a value as a string.
idRepository.addAttribute(username, attribute, "")

// idRepository.getAttribute(username, attribute).toString() > [,]

// Get the first value:
// idRepository.getAttribute(username, attribute).iterator().next()) >

// Get a value at the specified index:
// idRepository.getAttribute(username, attribute).toArray()[1] >

// If no attribute by this name is found, the result is an empty array:
// idRepository.getAttribute(username, "non-existent-attribute").toString() > []

outcome = "true"

Set session properties

A script can create session properties with the fields and methods of the Action interface.

The following example sets the outcome to true, and adds a custom session property:

  • JavaScript

var goTo = org.forgerock.openam.auth.node.api.Action.goTo
action = goTo("true").putSessionProperty("mySessionProperty", "myPropertyValue").build()

When adding a session property, make sure it is in the AM allow list. AM does not allow the script to add it to sessions unless it is in the allow list.

  1. In AM admin UI, under Realms > Realm Name > Services, make sure the Session Property Whitelist Service is configured.

    If not, configure the service with the default settings.

  2. Add the property name to the Allowlisted Session Property Names list unless it is already present.

For details, refer to Session Property Whitelist Service.

Add the script to a Scripted Decision node in your authentication tree. When a user authenticates successfully, AM adds the property to their session, as shown in the following output for session introspection:

  "username": "014c54bd-6078-4639-8316-8ce0e7746fa4",
  "universalId": "id=014c54bd-6078-4639-8316-8ce0e7746fa4,ou=user,o=alpha,ou=services,ou=am-config",
  "realm": "/alpha",
  "latestAccessTime": "2022-10-31T11:03:25Z",
  "maxIdleExpirationTime": "2022-10-31T11:33:25Z",
  "maxSessionExpirationTime": "2022-10-31T13:03:24Z",
  "properties": {
    "AMCtxId": "de5abe95-db97-4354-9d32-aab660ea23a3-4252446",
    "mySessionProperty": "myPropertyValue"

Access existing session properties

A script can access existing session properties during a session upgrade request with the existingSession.get method.


String existingSession.get(String propertyName)

Returns the string value of the named existing session property, or null, if the property is not set.

If the current request is not a session upgrade and does not provide an existing session, the existingSession variable is not declared. Check for a declaration before attempting to access the variable.

  • JavaScript

if (typeof existingSession !== 'undefined') {
    var existingAuthLevel = existingSession.get("AuthLevel")
} else {
    nodeState.putShared("errorMessage", "Variable existingSession not declared - not a session upgrade.")

outcome = "true"


A script can use callbacks to provide or prompt for additional information during the authentication process.

The following script uses the NameCallback callback to request a "Nickname" value from the user. It adds the nickname to the nodeState object for use by subsequent nodes in the authentication tree:

  • JavaScript

var fr = JavaImporter(

if (callbacks.isEmpty()) {
  action = fr.Action.send(new fr.NameCallback("Enter Your Nickname")).build()
} else {
  nodeState.putShared("Nickname", callbacks.get(0).getName())
  action = fr.Action.goTo("true").build()

outcome = "true";

For a list of supported callbacks, refer to Supported callbacks.

Accessing credentials and secrets

Scripts used in a scripted decision node can access the secrets configured in AM secret stores on the file system.

For example, a script can access credentials or secrets defined in a file system secret volume in order to make outbound calls to a third-party REST service, without hard-coding those credentials in the script.


String secrets.getGenericSecret(String secretId)

Returns the value of the specified secret ID.

If the secret ID is defined at the realm level, its value is returned; otherwise, the script returns the value defined at the global level.

Only secret IDs that begin with the string scripted.node. are accessible to scripts.

For more information on creating secret IDs in a secret store, refer to Secret stores.

Use the following functions to format the returned secret value:


Retrieve the secret value in byte[] format.


Retrieve the secret value in UTF-8 format.

The following example scripts show how to get the value (passwd) from a secret ID named They use the value in a basic authentication header to access the{user}/{passwd} service:

  • JavaScript

  • Groovy

var username = "demoUser"
var password = secrets.getGenericSecret("").getAsUtf8()

var auth = java.util.Base64.getEncoder().encodeToString(java.lang.String(username + ":" + password).getBytes())

var request = new org.forgerock.http.protocol.Request()
request.getHeaders().add("content-type","application/json; charset=utf-8")
request.getHeaders().add("Authorization", "Basic " + auth)

var response = httpClient.send(request).get()
var jsonResult = JSON.parse(response.getEntity().getString())
logger.error("Script result: " + JSON.stringify(jsonResult))
if (jsonResult.hasOwnProperty("authenticated")) {
    logger.error("outcome = success")
    outcome = "success"
}  else {
    logger.error("outcome = failure")
    outcome = "failure"
def username = "demoUser"
def password = secrets.getGenericSecret("").getAsUtf8()

def auth = java.util.Base64.getEncoder().encodeToString((username + ":" + password).getBytes())

def request = new org.forgerock.http.protocol.Request()
request.getHeaders().add("content-type","application/json; charset=utf-8")
request.getHeaders().add("Authorization", "Basic " + auth)

def response = httpClient.send(request).get()
if (response.status.successful) {
    logger.error("outcome = success")
    outcome = "success"
}  else {
    logger.error("outcome = failure")
    outcome = "failure"

To use these sample scripts, add the following classes to the class allowlist property in the AUTHENTICATION_TREE_DECISION_NODE scripting engine configuration:

  • org.mozilla.javascript.ConsString

  • java.util.Base64

  • java.util.Base64$Encoder

For details, refer to Security.

Audit information

Use a script to add information to audit log entries with the auditEntryDetail variable.

AM appends the value of the variable to the authentication audit logs.

For JavaScript, the variable must be a string. This example adds the username and email address to the log entry:

var username = nodeState.get("username").asString();
var email = idRepository.getAttribute(username,"mail").iterator().next().toString();

var detailStr = ("Extra Audit: [" + username + "] Email address: " + email).toString();
auditEntryDetail= detailStr;

outcome = "true";

AM records the audit string in the entries > info > nodeExtraLogging > auditInfo field of the authentication log entry:

    "_id": "31a9caa2-1439-4088-813f-a60c5f083a45-7725962",
    "timestamp": "2022-12-13T17:22:14.818Z",
    "eventName": "AM-NODE-LOGIN-COMPLETED",
    "transactionId": "31a9caa2-1439-4088-813f-a60c5f083a45-7725948",
    "trackingIds": [
    "principal": [
    "entries": [
            "info": {
                "nodeOutcome": "true",
                "treeName": "Example",
                "displayName": "Audit Entry",
                "nodeType": "ScriptedDecisionNode",
                "nodeId": "275a8aeb-7a61-4c70-acc2-decb1e0bc139",
                "authLevel": "0",
                "nodeExtraLogging": {
                    "auditInfo": "Extra Audit: [bjensen] Email address:"
    "realm": "/alpha",
    "component": "Authentication"

For more information about logging, refer to Audit logging.

Copyright © 2010-2023 ForgeRock, all rights reserved.