Common Procedure Objects

The following section defines some common utility objects that may be available to different procedures via the context object. Check each procedure type documentation for a comprehensive list of which objects are available for each type of procedure.

Note

Note that global scripts cannot make use of these objects unless they receive the context from a procedure as a function argument.

API

Objects available through the context object. See each procedure type for information on how to retrieve the object.

Account

accountAttributes

A map data structure representing the user account if it exists.

Request

httpRequest

A data structure representing a HTTP request as seen by the Server (i.e. the request sent by a HTTP Client).

Warning

When using any of these methods to obtain query string parameters, form parameters, and/or other input parameters and including those in the response and/or token issued by a procedure, the client should take all necessary measures to prevent opening up any security holes. Refer to Including Request Parameters Values for details.

httpRequest.getScheme()

Get the protocol scheme of the incoming request

Returns:the scheme as string
httpRequest.getClientIpAddress()

Get the callers IP address or the X-Forwarded-For value if that is set.

Returns:the IP address as string
httpRequest.getCookie(name)

Gets the value of the plaintext cookie with name name.

Arguments:
  • name (string) – the name of the cookie
Returns:

the value as string or null if cookie was not present

httpRequest.getSignedCookie(name)

Gets the value of the signed cookie with name name. The cookie is only returned if the signature is valid.

Arguments:
  • name (string) – the name of the cookie
Returns:

the value as string or null if cookie was not present

httpRequest.getEncryptedCookie(name)

Gets the decrypted value of the encrypted cookie with name name.

Arguments:
  • name (string) – the name of the cookie
Returns:

the value as string or null if cookie was not present

httpRequest.getHeader(name)

Gets the header value for the given header name

Arguments:
  • name (string) – the name of the header
Returns:

the value as string, null if not present or throws an error if multiple headers are present for the same name

httpRequest.getHeaders(name)

Gets the header values for the given header name.

Arguments:
  • name (string) – the name of the header
Returns:

the values as a list of Strings, or an empty list if not present.

httpRequest.getQueryString()

Gets the entire query string

Returns:the query string as string
httpRequest.getParameter(name)

Get the single value of a query- or form-parameter in the request.

If more than one value exists, a bad request Exception is thrown.

If the parameter is not given, null is returned.

Arguments:
  • name (string) – the name of the parameter
Returns:

the requested parameter as String

httpRequest.getParameterValues(name)

Get all values of a query- or form-parameter in the request.

If the parameter is not given, an empty Collection is returned.

Arguments:
  • name (string) – the name of the parameter
Returns:

the requested parameter values as a Collection of Strings

httpRequest.getParameterNames()

Get all query- and form-parameter names from the request

Returns:a set of names
httpRequest.getFormParameter(name)

Get the single value of a form parameter in the request.

If more than one value exists, a bad request Exception is thrown.

If the parameter is not given, null is returned.

Arguments:
  • name (string) – the name of the parameter
Returns:

the requested parameter as String

httpRequest.getFormParameterValues(name)

Get all values of a form parameter in the request.

If the parameter is not given, an empty Collection is returned.

Arguments:
  • name (string) – the name of the parameter
Returns:

the requested parameter values as a Collection of Strings

httpRequest.getFormParameterNames()

Get the names of all form parameters from the request

Returns:a set of names
httpRequest.getQueryParameter(name)

Get a named query parameter.

Arguments:
  • name (string) – the name of the parameter
Returns:

the requested parameter as String

httpRequest.getQueryParameterValues(name)

Get all values of a query parameter in the request.

If the parameter is not given, an empty Collection is returned.

Arguments:
  • name (string) – the name of the parameter
Returns:

the requested parameter values as a Collection

httpRequest.getQueryParameterNames()

Get the single value of a query parameter in the request.

If more than one value exists, a bad request Exception is thrown.

If the parameter is not given, null is returned.

Returns:a set of names
httpRequest.getUrl()

Get the full URL for this request. Note that if behind a reverse proxy this may represent the internal URL.

Returns:the URL address as String
httpRequest.getPath()

Get the path for this request

Returns:the Uri as String
httpRequest.getMethod()

Get the HTTP method for this request

Returns:the HTTP Method address as String

Response

httpResponse

A data structure representing a HTTP response as seen by the Server (i.e. the response that will be sent to a HTTP Client).

httpResponse.setSignedCookie(name, value, cookieOptions)

Sets a signed cookie as a session cookie, with the given name and value. If no cookieOptions are given, then a session cookie will be set with a lifetime of the browser session. The path of the cookie will be set to the path of the current request.

Arguments:
  • name (string) – The name of the cookie to set
  • value (string) – The string value of the cookie to set
  • options (map) – An optional map of cookieOptions
httpResponse.setEncryptedCookie(name, value, cookieOptions)

Sets an encrypted cookie as a session cookie, with the given name and value. If no cookieOptions are given, then a session cookie will be set with a lifetime of the browser session. The path of the cookie will be set to the path of the current request.

Arguments:
  • name (string) – The name of the cookie to set
  • value (string) – The string value of the cookie to set
  • options (map) – An optional array of cookieOptions

Example usage:

Listing 296 setEncryptedCookie example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function result(context) {
  ...
  var settings = {
    "maxAge" : 3600,
    "persist": true,
    "path" : "/authn"
  };

  context.response.setEncryptedCookie("myCookie", "someValue", settings);
}
cookieOptions

An object that can be passed to the setCookie operations of the response object.

  • maxAge : (integer) Duration in seconds that the cookie should be valid for. If not set the cookie will be a session cookie for the life of the browser window
  • persist: (boolean) Marks if the cookie should be a session cookie or persisted cookie. Note: if no maxAge is given, persist is ignored.
  • path : (string) A path to set the cookie on, if not set, the cookie will be set on the path for the current request.
  • samesite : (string) a string denoting the same site policy of the cookie. Acceptable values are strict, lax, and none. If no value or some other value is provided, no default will be used.
  • httpOnly : (boolean) false if the cookie should be accessible to JavaScript; true, unspecified or any other value if JavaScript clients should not be able to access the cookie.

Data Source

dataSource
Represents a handle to a data-source configured in the system.
dataSource.getAttributes(subjectMap)

Retrieves the attributes for the requested subject, or an empty object if it does not exist.

Arguments:
  • subjectMap (map) – A map containing attributes from the authentication, where the only mandatory field is subject.
Returns:

An attributesTable representing the subject’s attributes.

attributesTable

Retrieved by converting the attributes to a Table view.

Listing 297 Attributes as Table
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var subjectMap = {"subject": context.subject};
var attributes = dataStore.getAttributes(subjectMap);
var dataRows = attributes.allRows.iterator();
var attributeClaims = {};

 while (dataRows.hasNext()) {
     // row is a Map
     var row = dataRows.next();

     if (row.containsKey("linked_account_id") &&
         row.containsKey("linked_account_domain_name")) {

         console.log("Attributes found and contain linked account");

         // se.curity.identityserver.data.attribute.Attribute
         var linkedAccountId = row["linked_account_id"];
         var linkedAccountDomainName = row["linked_account_domain_name"];

         attribute_data["linked_accounts"].push({
             "id": linkedAccountId,
             "domain": linkedAccountDomainName
         });
     } else {
         console.log("Attributes do not contain linked account: " + attributes);
     }
 }
attributesTable.getRow(rowIndex)

Retrieves a row Object from the table of attributes if it exists, or null otherwise.

Arguments:
  • rowIndex (number) – The index of the table row.
Returns:

Object representing a table row.

attributesTable.getCell(rowIndex, columnName)

Retrieves a cell from the table of attributes if it exists, or null otherwise.

Arguments:
  • rowIndex (number) – The index of the table row.
  • columnName (string) – The name of the column in the table.
Returns:

a table cell.

attributesTable.getRowCount()
Returns:the number of rows in the table.
attributesTable.getAllRows()
Returns:array of all row Objects from the table of attributes.
attributesTable.getColumnValues(columnName)

Retrieves an array containing the value of the given column for each row.

Arguments:
  • columnName (string) – The name of the column in the table.
Returns:

array of all values for a particular column from the table of attributes. If a row does not contain a value for the column, null will be added to the array so that the array’s length is always the same as the row count.

Original Query Parameters

A collection of the query parameters used when initiating the authentication. Either to the Authorization Endpoint, or to the Authentication Endpoint.

originalQueryParameters

A collection of the query parameters.

Warning

When using any of these methods to obtain query string parameters, form parameters, and/or other input parameters and including those in the response and/or token issued by a procedure, the client should take all necessary measures to prevent opening up any security holes. Refer to Including Request Parameters Values for details.

originalQueryParameters.getQueryString()

The full query string used.

Returns:The query string
originalQueryParameters.get(parameterName)

Retrieves the first match of parameterName

Arguments:
  • parameterName (string) – The name of the parameter.
Returns:

The value of the first parameter with the given name. Null if not found

originalQueryParameters.getNames()

Retrieves the names of the parameters available in the collection.

Returns:A set of the parameter names.
originalQueryParameters.getAll(parameterName)

Retrieves all values with the name parameterName

Arguments:
  • parameterName (string) – The name of the parameter.
Returns:

A list of all the values for the given parameterName. Empty list if none found.

Exception Factory

exceptionFactory

A utility object for creating server-recognized Exceptions.

exceptionFactory.unauthorizedException(message[, realm])
Arguments:
  • message (string) – error message
  • realm (string) – (optional) realm
Returns:

the Exception object

exceptionFactory.forbiddenException(message)
Arguments:
  • message (string) – error message
Returns:

the Exception object

exceptionFactory.unauthorizedException(message)
Arguments:
  • message (string) – error message
Returns:

the Exception object

exceptionFactory.badRequestException([message])
Arguments:
  • message (string) – (optional) error message
Returns:

the Exception object

exceptionFactory.internalServerException([message])
Arguments:
  • message (string) – (optional) error message
Returns:

the Exception object

exceptionFactory.redirectException(redirectUri[, redirectStatusCode])
Arguments:
  • redirectUri (string) – redirect URI
  • redirectStatusCode (number) – (optional) redirect status code (301, 302)
Returns:

the Exception object

exceptionFactory.redirectException(message[, redirectUri, queryParameters])
Arguments:
  • message (string) – error message
  • redirectUri (string) – (optional) redirect URI
  • redirectStatusCode (number) – (optional) query parameters
Returns:

the Exception object

exceptionFactory.notFoundException()
Returns:the Exception object
exceptionFactory.error(errorCode, message)
Arguments:
  • errorCode (string) – error code
  • message (string) – error message
Returns:

the Exception object

Example usage:

Listing 298 ExceptionFactory example
1
2
3
4
5
6
function result(context) {
  ...
   //Respond with 400 Bad request
   throw exceptionFactory.badRequestException("your message here");
  ...
}

Tip

If you want your message to be visible in the server’s response you would need to enable expose-detailed-error-messages

Json (de-) Serializer

json

A JSON serializer/deserializer object.

This object can be used to (de)serialize any object, including Java and JS objects, unlike JavaScript’s JSON object, which can only handle JS objects.

json.toJson(object[, includeNulls])
Arguments:
  • object (any) – object to be serialized
  • includeNulls (boolean) – (optional) whether to include nulls (false by default)
Returns:

JSON String

json.fromJson(jsonString[, includeNulls])
Arguments:
  • jsonString (string) – JSON String to de-serialize into a Map (JS Object)
  • includeNulls (boolean) – (optional) whether to include nulls (false by default)
Returns:

deserialized JSON String as a Map

json.fromArray(jsonArrayString[, includeNulls])
Arguments:
  • jsonString (string) – JSON String to de-serialize into a List (JS Object)
  • includeNulls (boolean) – (optional) whether to include nulls (false by default)
Returns:

deserialized JSON String as a List

WebServiceClient

A HTTP client configured to send requests to a specific web server.

Example usage:

Listing 299 WebServiceClient usage
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
   var response = context.webServiceClient.get({
      path: "/some/resource",
      headers: { "Accept": "application/json" },
      query: { type: "thing", filter: ["value > 10", "account_id == 'joe'"] }
   });

   if (response.statusCode == 200) {
       // success
       logger.debug(response.body);
   } else {
       logger.warn("Something wrong");
   }
webServiceClient

A Web-service client.

webServiceClient.get([parameters])

Send a GET request to the configured web service.

Arguments:
  • parameters (map) – (optional) parameters to configure the request
Returns:

a ClientResponse object.

webServiceClient.post([parameters])

Send a POST request to the configured web service.

Arguments:
  • parameters (map) – (optional) parameters to configure the request
Returns:

a ClientResponse object.

webServiceClient.request(parameters)

Send a request to the configured web service. The HTTP method to use must be provided in the given parameters.

Arguments:
  • parameters (map) – parameters to configure the request
Returns:

a ClientResponse object.

parameters

Parameters that can be used to configured a request.

  • method : The HTTP method to use (ignored when the get() or post() methods are used).
  • path: The path of the request.
  • query: An object containing the query items. Each entry may contain a single value or an array of values.
  • headers: An object containing headers. Each entry may contain a single value or an array of values.
  • body: The body to send with the request (ignored if the method is GET).
  • timeout: read timeout in milli-seconds.

ClientResponse

ClientResponse

A HTTP Response received by a HTTP Client.

statusCode

The status code of the response.

headers

The HTTP response headers. See HttpHeaders.

body

The HTTP response body as a String.

bodyAsBytes

The HTTP response body as a byte array.

uri

The URI of the request for which this response was obtained.

HttpHeaders

httpHeaders

Represents the HTTP Headers of a Response or ClientResponse.

httpHeaders.firstValue(headerName)

Retrieves the first value of the header, or null if none is present.

Arguments:
  • headerName (string) – the name of the header.
Returns:

the value of the header, or null.

httpHeaders.firstValueAsLong(headerName)

Retrieves the first value of the header as a number, or null if none is present. If the value is present but cannot be converted to a number, an Exception is thrown.

Arguments:
  • headerName (string) – the name of the header.
Returns:

the value of the header as a number, or null.

httpHeaders.singleValueOrError(headerName)

Retrieves the only value of the header, null if none is present, or throw an Exception if more than one value exists.

Arguments:
  • headerName (string) – the name of the header.
Returns:

the value of the header, or null.

httpHeaders.allValues(headerName)

Retrieves all values of the header.

Arguments:
  • headerName (string) – the name of the header.
Returns:

all values of the header. An empty array is returned if the header is not present.

httpHeaders.map()

Retrieves all headers as a JS object in the form { <header_name>: [<value1>, <value2>, ...] }.

Returns:all headers.

SessionManager

sessionManager

The SessionManager service.

sessionManager.put(key, value)

Add a new entry into the session.

Arguments:
  • key (String) – the key of the data to add in the session
  • value (Comparable) – the value of the data to add in the session
sessionManager.remove(key)

Remove the data for the given key.

Arguments:
  • key (string) – the key to remove data for
Returns:

Object the data that was removed, or null if none was found

sessionManager.get(key)

Get the data for the given key.

Arguments:
  • key (string) – The key to lookup data for
Returns:

Object the stored data, or null if not found

sessionManager.getSessionId()

The session ID for the current session.

Returns:String ID of the current session
sessionManager.putIntoSession(sessionId, key, value)

Allows the caller to put data into another session.

Arguments:
  • sessionId (string) – the session ID for the session to place the data in
  • key (string) – the key of the data to add in the session
  • value (Comparable) – the value of the data to add in the session
Example usage:
Listing 300 SessionManager example
1
2
3
4
5
6
function result(context) {
  ...
  context.sessionManager.put("SomeKey", "SomeValue");
  ...
  var mySavedValue = context.sessionManager.get("SomeKey"); // mySavedValue = "SomeValue"
}

SmsSender

smsSender

The SmsSender service.

smsSender.sendSms(toNumber, msg)

Send a SMS message.

Arguments:
  • toNumber (string) – the number to send the SMS to.
  • msg (string) – the message to send.
Returns:

true if successful, false otherwise.

EmailSender

emailSender

The EmailSender service.

emailSender.sendEmail(recipient, emailModel, resource)

Send an Email message.

Arguments:
  • recipient (string) – the recipient’s email address.
  • emailModel (map) – the model for the template view to be sent as an email message.
  • resource (string) – the template resource to be sent as an email message.
emailSender.sendEmail(emailParameters)

Send an Email message.

Arguments:
emailParameters

Parameters that can be used to send an email message.

  • recipient: The email address to send the message to.
  • email: the model for the template view to be sent as an email message.
  • resource: the template resource to be sent as an email message.

AccountManager

accountManager

The accountManager object allows scripts to perform actions related to user accounts.

accountManager.supportsRegistration()

Checks if this accountManager supports registration.

Returns:true if registration is supported, false otherwise.
accountManager.isSetPasswordAfterActivation()

Retrieves the first value of the header, or null if none is present.

Checks if this accountManager is configured to set a password only after registration.

Returns:true if a password may be set after registration, false otherwise.
accountManager.initializeActivation(accountAttributes, model)

Retrieves the first value of the header, or null if none is present.

Arguments:
  • accountAttributes (map) – account to activate.
  • model (map) – a model to be used by the view generated for activation.
Returns:

the activationResult.

accountManager.activateAccount(token)

Activates an account based on a token.

Arguments:
  • token (string) – token that can be used to activate an account.
Returns:

the activationResult.

accountManager.getByUserName(userName)

Get a user account by userName.

Arguments:
  • userName (string) – account username.
Returns:

the account as a map, or null if none is found.

accountManager.getByEmail(email)

Get a user account by email address.

Arguments:
  • email (string) – account email address.
Returns:

the account as a map, or null if none is found.

accountManager.getByPhone(phone)

Get a user account by phone number.

Arguments:
  • phone (string) – account phone number.
Returns:

the account as a map, or null if none is found.

accountManager.createAccount(accountAttributes)

Create a user account.

Arguments:
  • accountAttributes (map) – account to be created.
accountManager.updateAccount(accountAttributes)

Update a user account.

Arguments:
  • accountAttributes (map) – account to be updated.
accountManager.ensureNonDuplicateAccount(userName, primaryEmail)

Ensure an account would not become duplicated with the provided userName or primaryEmail.

Arguments:
  • userName (string) – account username.
  • primaryEmail (string) – account primary email address.
Returns:

null if an account with the provided parameters would not become duplicated, or an error message if the account would become duplicated.

activationResult

The result of requesting the activation of a user account.

  • model : The response model map.
  • state: The state.
  • done: whether activation is done.
  • pending: whether activation is pending.
  • failed: whether activation failed.
  • username: account’s username.

CredentialManager

credentialManager

A credentialManager can be used to manage user credentials.

credentialManager.verifyPassword(subjectId, providedPassword[, context])

Verify a user’s password.

Arguments:
  • subjectId (string) – subject the password owner.
  • providedPassword (string) – the password that was presented for authentication.
  • context (string) – (optional) authentication context.
Returns:

true if verification succeeds, false otherwise.

credentialManager.transform(subjectId, providedPassword, password)

Transform the user’s password. This is usually done to encrypt the password before storing it.

Arguments:
  • subjectId (string) – subject the password owner.
  • providedPassword (string) – the password to be transformed.
  • password (string) – the current password, or null if unknown.
Returns:

the transformed password.

credentialManager.updatePassword(accountAttributes)

Update the password for the provided account. The account must contain the updated password.

Arguments:
  • accountAttributes (string) – the account whose password is being updated.