Conditional authentication - API reference


# Conditional authentication - API reference

Asgardeo provides a set of defined functions and objects to write your conditional authentication script. They are grouped as follows:


# Core functions

These are the basic functions that are required for defining the application login flow using an authentication script.

# Initial login request

onLoginRequest()

This function is called when Asgardeo receives the initial login request. It includes the parameters given below.

  • Parameters

    context The authentication context, which contains the context information about the request.
  • Example

    onLoginRequest(context)
    
    1

# Execute a step

executeStep()

This function is called to execute an authentication step in the login flow. You need to define your application's login flow before using this function.

This method accepts an object as a parameter and should include the details listed below.

<stepId> (Mandatory) The step number in the login flow.
<options> (Optional) A map that can configure step execution. Authentication option filtering is supported.
For more information, see the example on filtering connections in a step given below.
<eventCallbacks> (optional) The object that contains the callback functions, which are to be called based on the result of the step execution.
Supported results are onSuccess and onFail, which can have their own optional callbacks as anonymous functions.

The following sample template shows how the above categorization can be used in a script.

executeStep(<stepId>, 
{
  <options>:[
    //The objects of the option
  ]
},
{
  <eventCallback>: function()> {
    //eventCallback can be `onSuccess` or `onFail` 
    //Define what should be done
  }
});
1
2
3
4
5
6
7
8
9
10
11
12

# Parameters

This section describes the options you can use to configure the executeStep() function, and the values you can use as local authenticators and federated IdPs in the function.

  • Options

    You can use these options when executing an authentication step through the script. See the examples given below for details.

    authenticationOptions List the authentication methods that will be prompted for this step.
    authenticationOptions.authenticator The name of the local authenticator used.
    authenticationOptions.idp The name of the federated identity provider used.
    authenticatorParams Pass the configuration for the step authenticators or identity providers.
    authenticatorParams.common Specify the common configurations for both local authenticators and federated identity providers.
    authenticatorParams.local.{authenticator-name} The name of the local authenticator used in the application. The configurations passed here will be available for that specific authenticator.
    authenticatorParams.local.{federated-identity-provider} The name of the federated identity provider used in the application. The configurations passed here will be available for that federated identity provider.
  • Connections: Local authenticators and federated IdPs

    When you want to access your configured connections in an authentication step, you can use the following values through the options explained above.

    See the example on filtering connections in a step given below for details.

    The local authenticators are represented by the authenticator parameter. The table shows the connection names (as displayed on the Asgardeo Console) and the corresponding authenticator name you can use in the scripts.

    Connection Name Authenticator
    Email OTPemail-otp-authenticator
    Identifier FirstIdentifierExecutor
    Magic LinkMagicLinkAuthenticator
    Security Key/BiometricsFIDOAuthenticator
    SMS OTPsms-otp-authenticator
    TOTPtotp
    Username & PasswordBasicAuthenticator

    The external identity providers are represented by the idp parameter. The federated connection names are generated based on the name you assign to the connection at registration.

    Example

    If you add a federated google connection with the name bifrost google, the value you can use in your authentication scripts is bifrost_google.

# Examples

Shown below are ways to define a login flow using the core functions.

  • Example 1: Use stepId

    This example uses only the stepId.

    executeStep(1)
    
    1
  • Example 2: Use stepId and eventCallbacks

    This example uses only the stepId and eventCallbacks.

    executeStep(1, {
        onSuccess: function(context) {
            //Do something on success
        }
    });
    
    1
    2
    3
    4
    5
  • Example 3: Use all parameters

    This example uses the stepId, options, and an empty eventCallbacks object. Different properties can be defined by the options object, such as authenticationOptions and authenticatorParams. However, you cannot write a script with only the stepId and options. See the following two examples:

    executeStep(1, {
        authenticationOptions:[{
            authenticator: 'totp'
        }]}, {}
    );
    
    1
    2
    3
    4
    5
    executeStep(1, {
        authenticatorParams: {
            local: {
                email-otp-authenticator: {
                      enableRetryFromAuthenticator: 'true'
                }
            }
        }, {}
    );
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
  • Example 4: Filter connections in a step

    The authenticationOptions array filters out connections (local authenticators and federated identity providers) of a step based on a condition.

    This can be achieved by specifying an array named authenticationOptions to the options map. You can have idp as an array item for federated connections and authenticator as an array item for local connections, as shown below.

    executeStep(1,{
      authenticationOptions:[{authenticator:'BasicAuthenticator'},{idp:'google'}]
      },{
          onSuccess: function (context) {
              // Do something on success
    };
    
    1
    2
    3
    4
    5
    6

# Fail the login flow

fail()

This function redirects the user to the redirect URI provided in the authorization request when the login flow fails.

This function takes a map as an optional parameter. When a map is provided as the parameter, the redirect URL will be appended with the following properties (which should be contained in the map). Otherwise, the default parameters are passed. All the properties passed in the map are also optional.

  • Parameters

    errorCode The error code to be appended in the redirect URL.
    errorMessage The error message to be appended in the redirect URL.
    errorURI The URI of a web page that includes additional information about the error.
  • Example

    var parameterMap = {'errorCode': 'access_denied', 'errorMessage': 'login could not be completed', "errorURI":'http://www.example.com/error'};
    if (!isAuthenticated) {
        fail(parameterMap);
    }
    
    1
    2
    3
    4

# Redirect to error code

sendError()

This function redirects the user to an error page. It includes the parameters listed below.

  • Parameters

    url The URL of the error page that the user is redirected to. If the value is null, the user is redirected by default to the retry.do error page.
    Note that any relative URL is assumed to be relative to the host’s root.
    parameters Key value map passed as parameters. These are converted to query parameters in the URL.
  • Example

    It is recommended to use an i18n key to describe the error messages so that they can be internationalized easily on the error page.

    var user = context.steps[1].subject;
    var isAdmin = hasRole(user, 'admin');
    if (!isAdmin) {
        sendError('http://www.example.com/error',{'status':'000403','statusMsg':'You are not allowed to login to this app.', 'i18nkey':'not.allowed.error'});
    }
    
    1
    2
    3
    4
    5

# Utility functions

The implementation of utility functions can be found in the WSO2 extensions code repository (opens new window).

# Check group membership

isMemberOfAnyOfGroups()

This function returns true if the specified user belongs to at least one of the given groups, and returns false if the user does not. It includes the parameters listed below.

  • Parameters

    user A user object representing the user details.
    groups A list of strings that contain the groups. Each string is a group name.
  • Example

    var groups = ['admin', 'manager'];
    var user = context.steps[1].subject;
    var isMember = isMemberOfAnyOfGroups(user, groups);
    if (isMember) {
        executeStep(2);
    }
    
    1
    2
    3
    4
    5
    6

setCookie(response, name, value, properties)

This function sets a new cookie. It includes the parameters listed below.

  • Parameters

    response The HTTP response.
    name Name of the cookie.
    value Value of the cookie.
    properties

    A map that may contain optional attributes of the cookie with the two custom attributes given below.

    • sign: The default value is false. If it is set to true, the value will be signed.
    • encrypt: The default value is false. If it is set to true, the value will be encrypted.
  • Example

    The size of the value has to be less than the RSA key pair length if 'encrypt' is enabled (set to true).

    setCookie(context.response, "name", "test", {"max-age" : 4000,
                                                "path" : "/",
                                                "domain" : "localhost",
                                                "httpOnly" : true,
                                                "secure" : true,
                                                'sameSite': 'LAX',
                                                "version" : 1,
                                                "comment" : "some comments",
                                                "encrypt" : true,
                                                "sign" : true})
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

getCookieValue(request, name, properties)

This function gets the plain-text cookie value for the cookie name if it is present. It includes the parameters listed below.

  • Parameters

    request HTTP authentication request.
    name Name of the cookie.
    properties

    A map that may contain optional attributes of the cookie:

    • decrypt: The default value is false. If it is set to true, the value will be decrypted.
    • validateSignature: The default value is false. If it is set to true, the signature will be validated before returning a response.
  • Example

    getCookieValue(context.request,"name", {"decrypt" : true,"validateSignature" : true })
    
    1

# Prompt for user input

prompt()

This function prompts user input. It includes the parameters listed below.

  • Parameters

    templateId Identifier of the template that needs to be prompted.
    data The data to send to the prompt.
    eventHandlers The callback event handlers.
  • Example

    var onLoginRequest = function(context) {
      executeStep(1, {
          onSuccess: function (context) {
              var username = context.steps[1].subject.username;
              prompt("genericForm", {"username":username, "inputs":[{"id":"fname","label":"First Name"},{"id":"lname","label":"Last Name"}]}, {
                onSuccess : function(context) {
                    var fname = context.request.params.fname[0];
                    var lname = context.request.params.lname[0];
                    Log.info(fname);
                    Log.info(lname);
                }
              });
          }
      });
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

# Get user sessions

getUserSessions()

This function returns a session object (i.e., all the active user sessions of the specified user or an empty array if there are no sessions). It includes the parameters listed below.

  • Parameters

    user This is a user object that represents the user details.
  • Example

    var user = context.currentKnownSubject;
    var sessions = getUserSessions(user);
    for (var key in sessions) {
        Log.info(“Session ID:+ sessions[key].id);
    }
    
    1
    2
    3
    4
    5

# Terminate user session

terminateUserSession()

This function returns a session object (i.e., all the active user sessions of the specified user or an empty array if there are no sessions). It includes the parameters listed below.

  • Parameters

    user This is a user object that represents the user details.
    sessionId This is the sessionId string of the session that needs to be terminated.
  • Example

    var user = context.currentKnownSubject;
    var sessions = getUserSessions(user);
    if (sessions.length > 0) {
        var result = terminateUserSession(user, sessions[0]);
        Log.info(“Terminate Operation Successful?:+ result);
    }
    
    1
    2
    3
    4
    5
    6

# Send email

sendEmail()

This function sends an email to the specified user. It includes the parameters listed below.

  • Parameters

    user An object representing the user details.
    templateId Identifier of the email template. The email template specifies the body of the email that is sent out.
    placeholderParameters Used to replace any placeholders in the template.
  • Example

    var user = context.steps[1].subject;
    var firstName = user.localClaims['http://wso2.org/claims/givenname'];
    sendEmail(user, 'myTemplate', {'firstName':firstName});
    
    1
    2
    3

# Call a Choreo API

This function invokes an API hosted in Choreo (opens new window). It includes the parameters listed below.

Important

Note that to use the callChoreo function, the API should,

  • contain an endpoint that accepts POST requests.
  • return a status code of 2xx.
  • Parameters

    connectionMetadata An object containing the necessary metadata to invoke the API. . See ConnectionMetadata for more information.
    payloadData An object representing the payload that needs to be sent in the API request body.
    eventHandlers An object that contains the callback functions, which are to be called based on the result of API invocation.
    Supported results are onSuccess, onFail, and onTimeout.
  • Example

    var connectionMetadata = {
    "url": "<Choreo API URL>",
    "consumerKey": "<Consumer key of the Choreo Application>",
    "consumerSecret": "<Consumer secret of the Choreo Application>"
    };
    
    var requestPayload = {"example-key": "example-value"};
    
    callChoreo(connectionMetadata, requestPayload, {
      onSuccess: function(context, data) {
          Log.info("Successfully invoked the Choreo API.");
      },
      onFail: function(context, data) {
          Log.info("Error occurred while invoking the Choreo API.");
      },
      onTimeout: function(context, data) {
          Log.info("Invoking Choreo API timed out.");
      }
    });
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    Using Asgardeo as the key manager

    If you are using Asgardeo as the key manager in your Choreo organization, append the asgardeoTokenEndpoint parameter to the connectionMetadata variable as follows:

    var connectionMetadata = {
      "asgardeoTokenEndpoint": "https://api.asgardeo.io/t/<organization_name>/oauth2/token"
    };
    
    1
    2
    3

# Get parameter value from JWT

getValueFromDecodedAssertion(jwt, parameterName, isParameterInPayload)

This function returns a string containing the parameter's value in a decoded Json Web Token (JWT). It includes the following parameters:

  • Parameters

    jwt The JWT to be decoded.
    parameterName The name of the parameter in the JWT for which the value should be retrieved.
    isParameterInPayload Indicates whether the parameter to be retrieved is in the JWT header or body.
    Value should be true if the parameter to be retrieved is in the body.
  • Example

    var state = getValueFromDecodedAssertion(context.request.params.request[0],"state",true);
    
    1

# Get unique user

getUniqueUserWithClaimValues(claimMap, context)

The utility function will search the underlying user stores and return a unique user with the claim values. The claim map consists of the claim and value.

  • Parameters

    claimMap A map that contains the claim URI and claim value.
    context The authentication context, which contains the context information about the request.
  • Example

    var claimMap = {};
    claimMap[MAPPED_FEDERATED_USER_NAME_CLAIM] = federatedUserName;
    claimMap[MAPPED_FEDERATED_IDP_NAME_CLAIM] = idpName;
    var mappedUsername = getUniqueUserWithClaimValues(claimMap, context);
    
    1
    2
    3
    4

# Get associated user

getAssociatedLocalUser(federatedUser)

This function returns the local user associated with the federate username given as input.

  • Parameters

    federatedUser The federated user object.

# Object reference

# Context

Contains the authentication context information. The information can be accessed as follows:

context.steps[n] Access the authentication step information, where 'n' is the step number (1-based). See step for more information.

The step number is the one configured at the step configuration, not the actual order in which they get executed.

context.request Access the HTTP authentication request information. See request for more information.
context.response Access the HTTP response, which will be sent back to the client. See response for more information.
context.serviceProviderName Get the application name.

# Step

Contains the authentication step information. It may be a null or invalid step number.

step.subject Contains the authenticated user’s information from this step. It may be null if the step is not yet executed. See user for more information.
step.idp Gives the name of the federated connection that is used to authenticate the user.
step.authenticator Give the name of the authenticator that is used for authenticating the user. You can find the authenticator names from the connection names table.

# User

user.uniqueId The unique identifier of the user.
user.username The user’s username.
user.userStoreDomain (Read/Write)
The user store domain of the local user.
user.localClaims[“local_claim_url”] (Read/Write)
User’s attribute (claim) value for the given "local_claim_url". If the user is a federated user, this will be the value of the mapped remote claim from the identity provider.
user.claims[“local_claim_url”] (Read/Write)
Sets a temporary claim value for the session.
user.localClaims[“local_claim_url”] Updates the claim value in the user store as well. The user.claims[“local_claim_url”] parameter is an alternative to setting a temporary claim.
user.remoteClaims[“remote_claim_url”] (Read/Write)
User’s attribute (claim) as returned by the identity provider for the given remote_claim_url. Applicable only for federated users.

# Request

request.headers[“header_name”] The request’s header value for the given header name.
request.params.param_name[0] The request’s parameter value for the given parameter name by the param_name index (param_name is an array).
request.cookies[“cookie_name”] The request’s cookie value for the given cookie name.
request.ip The client IP address of the user who initiated the request. If there are any load balancers (eg. Nginx) with connection termination, the IP is retrieved from the headers set by the load balancer.

# Response

response.headers[“header_name”] (Write) The response header value for the given header name.

# Session

session.userAgent This is the userAgent object of the user session. See userAgent for more information.
session.ip This is the session’s IP address.
session.loginTime This is the session’s last login time.
session.lastAccessTime This is the session’s last accessed time.
session.id This is the session’s ID.
session.applications This is the list of application objects in the session. See application for more information.

# Application

application.subject This is the subject of the application.
application.appName This is the name of the application.
application.appId This is the ID of the application.

# User agent

userAgent.raw This is the raw userAgent string.
userAgent.browser This is the web browser property that is extracted from the raw userAgent string.
userAgent.platform This is the operating system property that is extracted from the raw userAgent string.
userAgent.device This is the device property that is extracted from the raw userAgent string.

# ConnectionMetadata

It contains the necessary metadata for invoking the API when calling the callChoreo function.

connectionMetadata.url URL of the Choreo hosted API.
connectionMetadata.consumerKey The consumer key of the Choreo application.
connectionMetadata.consumerSecret The consumer secret of the Choreo application.

If the consumer key and the consumer secret are added as secrets, they should be included in the ConnectionMetadata as aliases, as shown below.

connectionMetadata.consumerKeyAlias The name of the secret that stores the consumer key.
connectionMetadata.consumerSecretAlias The name of the secret that stores the consumer secret.