This site contains the documentation that is relevant to older WSO2 product versions and offerings.
For the latest WSO2 documentation, visit https://wso2.com/documentation/.

Adaptive Authentication JS API Reference

With adaptive authentication, it is possible to configure dynamic sequences based on runtime parameters such as the user’s IP address, user role, etc. WSO2 Identity Server allows you to define a dynamic authentication sequence using authentication scripts written in JavaScript. 

For more information on adaptive authentication, see Adaptive Authentication.

The following sections present the core API reference for the JavaScript-based conditional authentication functions and fields. 

As the authentication script is designed as a loosely typed, functional language similar to JavaScript, common knowledge on JavaScript may help you to compose effective authentication scripts.

Core functions

onLoginRequest(context)

This function is called when the initial authentication request is received by the framework. It includes the following parameters.

ParameterDescription
contextThe authentication context, which contains the context information about the request.
executeStep(stepId, options, eventCallbacks)

This function is called to execute an authentication step. Authentication steps need to be configured prior to using this function. This method accepts an object as a parameter and should include the following.

ParameterDescription
stepIdThe step number (mandatory)
optionsAn optional map that can configure step execution. Authentication option filtering is supported.
For more information, see  authentication step filtering .
eventCallbacks

The object that contains the callback functions that 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 (optional).

onSuccess - This event callback is called when the current step or authenticator results in success. If the step includes an authenticator, the authenticator has successfully identified the subject. Depending on the respective authenticators functionality, it could also mean that the authenticator has retrieved the claims succesfully.
 
onFail  -  This event handler is called when the step has failed. If the step includes an authenticator, this means that the user authentication for that authenticator has failed. Having the  onFail  event handler usually disables the default retry mechanism so as to provide the full control to the script writer. Hence, you have to implement retry logic in the script itself if the onFail  event handler is present for any "executeStep" function.

The API can be called in either of the following ways:

  • With only the stepId. Example:

    executeStep(1)
  • With only the stepId and eventCallbacks. Example:

    executeStep(1, {
    	onSuccess: function(context) {
    		//Do something on success
    	}
    });
  • With the stepId, options, and an empty eventCallbacks array. Example:

    executeStep(1,{
    	authenticationOptions:[{
    		authenticator: 'totp'
    	}]},
    });

    The API cannot be called with only the stepId and options .


Authentication step filtering

Filters out some of the authentication options of a step based on some condition. This can be achieved by specifying an array named ‘authenticationOptions’ to the options map. Each array item will require an ' idp' for federated IdPs or an ' authenticator' for local authenticators.

Example code
executeStep(1,{
   authenticationOptions:[
      {authenticator:'basic'},{idp:'google'}
   ]} ,{
   onSuccess: function (context) {
       // Do something on success
   }
});

Utility functions

The implementation of utility functions can be found in the  WSO2 extensions code repository .

hasRole(user, role)

This function returns true if the specified ‘ user ’ belongs to the specified ‘ role ', and returns false if the user does not. It includes the following parameters. 

ParameterDescription
userA user object representing the user details.
roleA string representing the role name.
Example code
var user = context.steps[1].subject;
var isAdmin = hasRole(user, 'admin');
Log.info('--------------- Has Admin ' + isAdmin);
if (isAdmin) {
    executeStep(2);
}
assignUserRoles(user, assigningRoles)

This function assigns each of the roles specified in the ‘ assigningRoles ’ parameter to the specified ‘ user ’ object. It returns true if all the roles are successfully assigned and returns false if not.  It includes the following parameters. 

ParameterDescription
userAn object representing the user details.
assigningRolesA list of strings containing roles that are to be assigned where each string is a role name.
executeStep(1, {
    onSuccess: function (context) {
        // Extracting authenticated subject from the first step.
        let user = context.currentKnownSubject;
        assignUserRoles(user, ['exampleRole1', 'exampleRole2']);
    }
});
removeUserRoles(user, removingRoles)

This function r emoves each of the roles specified in the ‘ removingRoles ’ parameter to the given ‘ user ’ object. It returns true if all the roles are successfully removed and returns false if not. It includes the following parameters. 

ParameterDescription
userAn object representing the user details.
removingRolesA list of strings that containing roles that are to be removed where each string is a role name.
executeStep(1, {
    onSuccess: function (context) {
        // Extracting authenticated subject from the first step.
        let user = context.currentKnownSubject;
        removeUserRoles(user, ['exampleRole1', 'exampleRole2']);
    }
});


sendEmail(user, templateId, placeholderParameters)

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

ParameterDescription
userAn object representing the user details.
templateIdIdentifier of the email template. The email template specifies the body of the email that is sent out.
placeholderParametersUsed to replace any placeholders in the template.
Example code
var user = context.steps[1].subject;
var firstName = user.localClaims['http://wso2.org/claims/givenname'];
sendEmail(user, 'myTemplate', {'firstName':firstName});
sendError(url,parameters)

This function redirects the user to an error page indicating the end of the authorization flow. The error page includes the following parameters. 

ParameterDescription
urlThe 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 as the relative to host’s root.  
parametersKey value map passed as parameters. These are converted to query parameters in the URL.
Example code
var user = context.steps[1].subject;
var isAdmin = hasRole(user, 'admin');
if (!isAdmin) {
    sendError('http://www.example.com/error',{'errorcode':'000403','errorMsg':'You are not allowed to login to this app.'});
}

Tip: When passing error messages to the error page, it is recommended to use the i18n key so that it can be internationalized easily at the page.

setCookie(response, name, value, properties)

This functions sets a new cookie. It includes the following parameters. 

ParameterDescription
nameName of the cookie.
valueValue of the cookie.
properties

A map that may contain optional attributes of the cookie with two other custom attributes ‘ encrypt ’ and ‘ sign ’.

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

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,
											"version" : 1,
											"comment" : "some comments",
											"encrypt" : true,
											"sign" : true})
getCookieValue(request, name, properties)

This function gets the plain-text cookie value for the cookie ‘ name ’ if present.  It includes the following parameters. 

ParameterDescription
nameName of the cookie.
valueValue of the cookie.
properties

A map that may contain optional attributes of the cookie ‘ de crypt validateSignature

  • The default value of ' decrypt ' is false.  If it is set to true, the value will be decrypted.
  • The default value of ' validateSignature ' is false.  If it is set to true, the signature will be validated before returning a response. 
getCookieValue(context.request,"name", {"decrypt" : true,"validateSignature" : true })
callAnalytics( metadata, payloadData, eventHandlers )

This function calls the analytics engine (i.e., WSO2 Stream Processor) to get a decision. It includes the following parameters. 

ParameterDescription
metadata

A JSON object that contain the following attributes:

    • Application: Siddhi application name (mandatory)

    • InputStream: Input stream name (mandatory)

payloadDataThe data that needs to be sent to the analytics engine. 
eventHandlersThe callback event handlers. 
publishToAnalytics( metadata, payloadData )

This function publishes data to the analytics engine (WSO2 Stream Processor). It includes the following parameters. 

ParameterDescription
metadata

A JSON object that contain the following attributes:

    • Application: Siddhi application name (mandatory)

    • InputStream: Input stream name (mandatory)

payloadDataThe data that needs to be sent to the analytics engine. 
prompt(templateId, data, eventHandlers)

This function prompts for user input. It includes the following parameters. 

ParameterDescription
templateId

Identifier of the template that needs to be prompted.

dataThe data to send to the prompt. 
eventHandlersThe callback event handlers. 
function onLoginRequest(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);
			 }
		   });
       }
   });
}

Object Reference

context Object

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 Object for more information.

    Note: 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 Object for more information.
  • context.response:  Access the HTTP response which will be sent back to the client. See response Object for more information.
  • context.serviceProviderName:  Get the application name.
step Object

Contains the authentication step information. May be null or invalid step number.

  • step.subject:  Contains the authenticated user’s information from this step. May be null if the step is not yet executed. See user Object for more information. 
  • step.idp:  Gives the Idp name which was used to authenticate this user.
user Object
  • user.username : The user’s username.
  • user.tenantDomain : The user’s tenant domain (only for local users; federated users will have this as carbon.super).
  • user.userStoreDomain : The user’s user store domain (only for local users).
  • user.roles : List of user’s roles.
  • 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 IdP.
  • user.remoteClaims[“<remote_claim_url”] : (Read/Write) User’s attribute (claim) as returned by IdP for the given “remote_claim_url”. Applicable only for federated users.
request Object
  • request.headers[“<header_name>”] : Request’s header value for the given header name by <header_name>
  • request.params[“<param_name>”] : Request’s parameter value for the given parameter name by <parameter_name>
  • request.cookies[“<cookie_name”] : Request’s cookie value for the given cookie name by <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 Object
  • request.headers[“<header_name>”] : (Write) Response header value for the given header name by <header_name>