Conditional authentication - API reference¶
WSO2 Identity Server 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 used in the script. These are used to identify the user who initiated the login flow, execute a step in the login flow, handle login failures, etc. Listed below are the core functions that can be used in conditional authentication scripts.
-
Utility functions: These utility functions are used for specific scenarios. For example, checking whether the login user belongs to a specific user group. Listed below are the utility functions that can be used in conditional authentication scripts.
-
Object references: You can use objects to capture user behaviors and set attributes. For example, you can use the user and request objects and write the login conditions accordingly. Listed below are the object references that can be used in conditional authentication scripts.
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 WSO2 Identity Server 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)
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
}
});
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 WSO2 Identity Server Console) and the corresponding authenticator name you can use in the scripts.Connection Name Authenticator Email OTP email-otp-authenticator Identifier First IdentifierExecutor Magic Link MagicLinkAuthenticator Passkeys FIDOAuthenticator SMS OTP sms-otp-authenticator TOTP totp Username & Password BasicAuthenticator 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)
-
Example 2: Use
stepId
andeventCallbacks
This example uses only the
stepId
andeventCallbacks
.executeStep(1, { onSuccess: function(context) { //Do something on success } });
-
Example 3: Use all parameters
This example uses the
stepId
,options
, and an emptyeventCallbacks
object. Different properties can be defined by theoptions
object, such asauthenticationOptions
,authenticatorParams
andstepOptions
. However, you cannot write a script with only thestepId
andoptions
.See the following examples:
executeStep(1, { authenticationOptions:[{ authenticator: 'totp' }]}, {} );
executeStep(1, { authenticatorParams: { local: { email-otp-authenticator: { enableRetryFromAuthenticator: 'true' } } }, {} );
executeStep(1, { stepOptions: { forceAuth: 'true' }, {} );
-
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 theoptions
map. You can haveidp
as an array item for federated connections andauthenticator
as an array item for local connections, as shown below.executeStep(1,{ authenticationOptions:[{authenticator:'BasicAuthenticator'},{idp:'google'}] },{ onSuccess: function (context) { // Do something on success };
-
Example 5: Force authentication with
stepOptions
The
stepOptions
is an optional property that can be defined in theexecuteStep
. This allows the addition of theforceAuth
authentication option, which can prompt the authenticator in the steps to re-authenticate, even if it was already authenticated.executeStep(1,{ stepOptions: { forceAuth: 'true' }, {} };
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); }
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 isAdmin = hasAnyOfTheRolesV2(context, ['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'}); }
Utility functions¶
The implementation of utility functions can be found in the WSO2 extensions code repository.
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); }
Set cookie¶
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 isfalse
. If it is set to true, the value will be signed.encrypt
: The default value isfalse
. 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})
Get cookie value¶
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 isfalse
. If it is set totrue
, the value will be decrypted.validateSignature
: The default value isfalse
. If it is set totrue
, the signature will be validated before returning a response.
-
Example
getCookieValue(context.request,"name", {"decrypt" : true,"validateSignature" : true })
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); } }); } }); }
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); }
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); }
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});
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 betrue
if the parameter to be retrieved is in the body. -
Example
var state = getValueFromDecodedAssertion(context.request.params.request[0],"state",true);
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["http://wso2.org/claims/username"] = federatedUserName; var mappedUsername = getUniqueUserWithClaimValues(claimMap, context);
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.
HTTP GET¶
httpGet(url, headers)
The HTTP GET function enables sending HTTP GET requests to specified endpoints as part of the adaptive authentication scripts in WSO2 Identity Server. It's commonly used to interact with external systems or APIs to retrieve necessary data for authentication decisions.
-
Parameters
url
The URL of the endpoint to which the HTTP GET request should be sent. headers
HTTP request headers to be included in the GET request (optional). -
Example
function onLoginRequest(context) {
httpGet('https://example.com/resource', {
"Authorization": "Bearer token",
"Accept": "application/json"
}, {
onSuccess: function(context, data) {
Log.info('httpGet call succeeded');
context.selectedAcr = data.status;
executeStep(1);
},
onFail: function(context, data) {
Log.info('httpGet call failed');
context.selectedAcr = 'FAILED';
executeStep(2);
}
});
}
Note
To restrict HTTP GET requests to certain domains, configure the deployment.toml
file as follows:
[authentication.adaptive]
http_function_allowed_domains = ["example.com", "api.example.org"]
HTTP POST¶
httpPost(url, body, headers)
The HTTP POST function enables sending HTTP POST requests to specified endpoints as part of the adaptive authentication scripts in WSO2 Identity Server. It's commonly used to interact with external systems or APIs to retrieve necessary data for authentication decisions.
-
Parameters
url
The URL of the endpoint to which the HTTP POST request should be sent. body
HTTP request body to be included in the POST request. headers
HTTP request headers to be included in the POST request (optional). -
Example
function onLoginRequest(context) {
httpPost('https://example.com/resource', {
"email": "[email protected]"
}, {
"Authorization": "Bearer token",
"Accept": "application/json"
}, {
onSuccess: function(context, data) {
Log.info('httpPost call succeeded');
context.selectedAcr = data.status;
executeStep(1);
},
onFail: function(context, data) {
Log.info('httpPost call failed');
context.selectedAcr = 'FAILED';
executeStep(2);
}
});
}
Note
To restrict HTTP POST requests to certain domains, configure the deployment.toml
file as follows:
[authentication.adaptive]
http_function_allowed_domains = ["example.com", "api.example.org"]
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 te 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 |
The user agent object of the user session. See userAgent for more information. |
session.ip |
The session's IP address. |
session.loginTime |
The session's last login time. |
session.lastAccessTime |
The session's last accessed time. |
session.id |
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. |