Policy Script Functions and Methods

You can use pre-defined methods in your JavaScript when developing a policy script.

Policy Script Functions

We recommend using the following functions for the policy script methods:

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 */
function onInitialize(config, context) {
}

/*
* @param config - object of type PolicyConfiguration
* @param context - object of type PolicyContext;
* @param result - object of type UserIdentifiedLoginResult;
*/
function onUserIdentified(config, context, result) {
}

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 * @param result - object of type FirstStageLoginResult;
 */
function onFirstStageLogin(config, context, result) {
}

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 * @param result - object of type SecondStageLoginResult; 
 */
function onSecondStageLogin(config, context, result) {
}

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 */
function onAbort(config, context) {
}

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 */
function onLogout(config, context) {
}

You can use the following functions for a context-based authorization:

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 * @param result - object of type FirstStageLoginResult;
 */
function onLimitedAccessSelected(config, context, result) {
}

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 * @param result - object of type FirstStageLoginResult;
 */
function onFullAccessSelected(config, context, result) {
}

You can also use the following function for external passcode validation:

/*
 * @param config - object of type PolicyConfiguration
 * @param context - object of type PolicyContext;
 * @param result - object of type PasscodeValidationLoginResult;
 * @param username - object of type String;
 * @param passcode - object of type String;
 */
function validatePasscode(config, context, result, username, passcode) {
}

Policy Script Methods

Object

Method

Description

PolicyConfiguration

getProperty(name)

Returns the value of the policy configuration property.

The name parameter is of type String and specifies the name of the requested property.

setProperty(name, value)

Sets a property of the policy configuration.

The name and value parameters are of type String and specify the name of the property and the assigned value.

Example
if (context.getHttpClientContext().getClientIP() == "10.11.12.13") {
    config.setProperty("tfa.first.factor.login.module", "SPNegoLoginModule");
} else {
    config.setProperty("tfa.first.factor.login.module", "BasicPasswordLoginModule");
}

PolicyContext

getLogger()

Returns a LogAccessor object for the policy context. The returned object is used for logging and tracing.

Example
var logger = context.getLogger();
var now = new Date();
logger.traceDebug("Logon time: " + now);

getNaming()

Returns an javax.naming.InitialContext object used for looking up with Java Naming and Directory Interface (JNDI).

getHttpClientContext()

Returns an HttpClientContext object.

Example
if (context.getHttpClientContext().getClientIP() == "10.11.12.13") {
    config.setProperty("tfa.first.factor.login.module", "SPNegoLoginModule");
} else {
    config.setProperty("tfa.first.factor.login.module", "BasicPasswordLoginModule");
}

getRsaContext()

Returns an RSAContext object.

Example
var rsaContext = context.getRsaContext();
if (rsaContext.validatePasscode(username, passcode) == rsaContext.VALID_PASSCODE){
    result.setValidationSuccessful();
}

getRadiusContext()

Returns an RADIUSContext object.

Example
var radiusContext = context.getRadiusContext();
if (radiusContext.validatePasscode(username, passcode) == radiusContext.VALID_PASSCODE){
    result.setValidationSuccessful();
}

getLoginInfo()

Returns a LoginInfo object used for logon information such as logon user, authentication method, and validity of user account.

Note

The method returns null when the first stage logon was not completed.

Example
var loginInfo = context.getLoginInfo();
var user = loginInfo.getUser();

createVirtualUserPrincipalBuilder(name, authenticationMethod)

Returns Builder for VirtualUserPrincipal. The principal has name and authentication method as specified as parameters.

By calling the build() method of this builder, a VirtualUserPrincipal is returned and can be set in the result of the onUserIndetified method. The methods of this builder are:
  • withGroups(<group1_name>, <group2_name>, …) – one or more parameters of type String
  • withRoles(<role1_name>, <role2_name>, …) – one or more parameters of type String
  • withAttribute(namespace, name, value) – parameters are of type String
  • withAttributeDefaultNamespace(name, value) – the default namespace will be used (“com.sap.security.core.usermanagement”); parameters are of type String
  • withBinaryAttribute(namespace, name, value)– namespace and name are of type String, value is of type byte
  • withBinaryAttributeDefaultNamespace(name, value) – the default namespace will be used (“com.sap.security.core.usermanagement”); namespace and name are of type String, value is of type byte
Example
function onUserIndetified(config, context, result) {
var virtualUserPrincipalBuilder = context.createVirtualUserPrincipalBuilder(“username” , “virtual_user”);
var virtualUserPrincipal = virtualUserPrincipalBuilder.withGroups(“group1”, “group2”).withRoles(“role1”, “role2”).withAttribute(“com.sap.security.core.usermanagement”, “email”, john.doe@example.com).withAttributeDefaultNamespace(“phone”, “+359000000000”).build();
result.setPrincipal(virtualUserPrincipal);
}

createPrincipal(name, authenticationMethod)

Returns Principal with name and authentication method as specified as parameters.

Example
context.createPrincipal(“username”, “client_cert”);

FirstStageLoginResult

setRandomPasscode(length, validity, maximumFailedAttempts, message)

Generates a random passcode and returns the passcode as String.

Parameters:

  • length - passcode length, of type int

  • validity - passcode validity in minutes, of type int

  • maximumFailedAttempts - the allowed passcode logon attempts before the account is locked, of type int

  • message - the text shown on the logon page, of type String.

Example
var passcode = result.setRandomPasscode(10, 15, 5, "Passcode sent via SMS; enter the passcode to log on");

setPasscode(passcode, validity, maximumFailedAttempts, message)

Sets a generated passcode.

Parameters:

  • passcode - the generated passcode, of type String

  • validity - passcode validity in days, of type int

  • maximumFailedAttempts - the allowed passcode logon attempts before the account is locked, of type int

  • message - the message text shown on the logon page, of type String.

doNotRequireSecondFactor()

Sets the application not to require a second factor after first stage logon.

Example

The script may not require a second factor if the user is not a manager.

if (!user.isMemberOfGroup('GRUP.PRIVATE_DATASOURCE.un:Managers', true)) {
    result.doNotRequireSecondFactor();
}

setOptionalSecondFactor()

Allows the user to decide whether to use a second factor.

If you use this method, the application's logon page displays the default text:

Select your access permission to log on:

(*) Limited Access Permissions (Log on directly)

( ) Full Access Permissions (Log on with a passcode)

[Continue] [Cancel]

setOptionalSecondFactor(message, firstOption, secondOption, defaultSelection)

Allows the user to decide whether to use a second factor, and customizes the default text according to the specified parameters.

Parameters:

  • message, firstOption, and secondOption parameters are of type String.

  • defaultSelection is a parameter with two values: result.DEFAULT_SELECTION_LIMITED_ACCESS, and result.DEFAULT_SELECTION_FULL_ACCESS.

Example

The following example selects the first option by default.

result.setOptionalSecondFactor("Select your access permissions to log on:", "Limited Permissions", "Manager's Permissions", result.DEFAULT_SELECTION_LIMITED_ACCESS);

setAuthorizationScopes(scopes,roleWithoutScopes)

Users are assigned roles in the user management engine (UME). Some of the roles can also contain scopes. The setAuthorizationScopes(scopes, roleWithoutScopes) method dynamically assigns to users those roles which comply with the specified parameters.

Parameters:

  • scopes - a string array of scopes. Users receive their UME roles that contain the specified scopes. If no scopes are specified in the brackets, the roleWithoutScopes parameter is taken into consideration.

  • roleWithoutScopes - a parameter with two values:
    • result.GRANT_ROLES_WITHOUT_SCOPES - the UME roles without scopes are granted.

    • result.DENY_ROLES_WITHOUT_SCOPES - the UME roles without scopes are not granted.

Example

The following example grants full access to users with UME roles containing the "FULL_ACCESS" scope and with UME roles that do not have scopes.

result.setAuthorizationScopes(["FULL_ACCESS"], result.GRANT_ROLES_WITHOUT_SCOPES);

abortLogin(message)

Resets the authentication process, that is, any previous results stored in the session are removed.

The message parameter is used to specify the message that the user receives when the logon is terminated.

Example

result.abortLogin("You are not allowed to log on outside of the working hours");

SecondStageLoginResult

abortSecondStage(message)

Aborts only the logon for the second stage, but not the whole authentication process.

The message parameter is used to specify the message that the user receives when the logon is terminated.

setAuthorizationScopes(scopes,roleWithoutScopes)

Users are assigned roles in the user management engine (UME). Some of the roles can also contain scopes. The setAuthorizationScopes(scopes, roleWithoutScopes) method dynamically assigns to users those roles which comply with the specified parameters.

Parameters:

  • scopes - a string array of scopes. Users receive their UME roles that contain the specified scopes. If no scopes are specified in the brackets, the roleWithoutScopes parameter is taken into consideration.

  • roleWithoutScopes - a parameter with two values:
    • result.GRANT_ROLES_WITHOUT_SCOPES - users are granted all their UME roles without scopes.

    • result.DENY_ROLES_WITHOUT_SCOPES - users are not granted all their UME roles without scopes.

Example

The following example grants full access to users with UME roles containing the "FULL_ACCESS" scope and with UME roles that do not have scopes.

result.setAuthorizationScopes(["FULL_ACCESS"], result.GRANT_ROLES_WITHOUT_SCOPES);

abortLogin(message)

Resets the authentication process, that is, any previous results stored in the session are removed.

The message parameter is used to specify the message that the user receives when the logon is terminated.

UserIdentifiedLoginResult

setPrincipal(principal)

Sets Principal as specified by the principal parameter.

The message parameter is used to specify the message that the user receives when the logon is terminated.

setAuthorizationScopes(scopes,roleWithoutScopes)

Users are assigned roles in the user management engine (UME). Some of the roles can also contain scopes. The setAuthorizationScopes(scopes, roleWithoutScopes) method dynamically assigns to users those roles which comply with the specified parameters.

Parameters:
  • scopes - a string array of scopes. Users receive their UME roles that contain the specified scopes. If no scopes are specified in the brackets, the roleWithoutScopes parameter is taken into consideration.
  • roleWithoutScopes - a parameter with two values:
    • result.GRANT_ROLES_WITHOUT_SCOPES - users are granted all their UME roles without scopes
    • result.DENY_ROLES_WITHOUT_SCOPES - users are not granted all their UME roles without scopes
Example
The following example grants full access to users with UME roles containing the "FULL_ACCESS" scope and with UME roles that do not have scopes.
result.setAuthorizationScopes(["FULL_ACCESS"], 
result.GRANT_ROLES_WITHOUT_SCOPES);

abortLogin(message)

Resets the authentication process, that is, any previous results stored in the session are removed.

The message parameter is used to specify the message that the user receives when the logon is terminated.

Logger

traceError(message)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Error.

The message parameter is of type String.

traceError(message, throwable)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Error.

Parameters:

  • message - of type String

  • throwable - indicates the thrown exception, of type Object

traceWarning(message)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Warning.

The message parameter is of type String.

traceWarning(message, throwable)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Warning.

Parameters:

  • message - of type String

  • throwable - indicates the thrown exception, of type Object

traceInfo(message)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Info.

The message parameter is of type String.

traceDebug(message)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Debug.

The message parameter is of type String.

traceDebug(message, throwable)

The trace showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Debug.

Parameters:

  • message - of type String

  • throwable - indicates the thrown exception, of type Object

logError(message)

The log showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Error.

The message parameter is of type String.

logWarning(message)

The log showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Warning.

The message parameter is of type String.

logInfo(message)

The log showing the message text in the log viewer of SAP NetWeaver Administrator with severity level Info.

The message parameter is of type String.

HttpClientContext

getClientIP()

Returns the IP of the client that the request is coming from. The returned value is String.

getHeader(name)

Returns the header value as String.

The name parameter is of type String.

Example

To return the value of the Host header, call the following method:

getHeader("Host")

setHeader(name, value)

Creates or sets a header with the specified value.

The name and value parameters are of type String.

removeHeader(name)

Removes the specified header.

The name parameter is of type String.

getCookie(name)

Returns the cookie value as String.

setPersistentCookie(name, value, path, domain, validity, httpOnly, secure)

Creates or sets a persistent cookie with the specified attributes.

Parameters:

  • The name, value, path, and domain parameters are of type String.

  • The validity parameter indicates the cookie's validity in seconds and is of type long.

  • The httpOnly and secure parameters are of type boolean.

setSessionCookie(name, value, path, domain, httpOnly, secure)

Creates or sets a session cookie with the specified attributes.

Parameters:

  • The name, value, path, and domain parameters are of type String.

  • The httpOnly and secure parameters are of type Boolean.

removeCookie(name, path, domain)

Removes a session or persistent cookie with the specified attributes.

The name, path, and domain parameters are of type String.

isSecure()

Checks if the cookie is secure and returns boolean: true if the cookie is secure, and false otherwise.

getParameter(name)

Returns the first value of the specified parameter in the Request as String.

The name parameter is of type String.

getParameterValues(name)

Returns the values of the specified parameter in the Request as a String[] array.

The name parameter is of type String.

getRequestAttribute(name)

Returns the value of the specified attribute in the Request as String.

The name parameter is of type String.

setRequestAttribute(name, value)

Creates or sets the attribute in the Request with the specified value.

The name and value parameters are of type String.

getSessionAttribute(name)

Returns the value of the session attribute as String.

The name parameter is of type String.

setSessionAttribute(name, value)

Creates or sets the session attribute with the specified value.

The name and value parameters are of type String.

removeSessionAttribute(name)

Removes the specified session attribute.

The name parameter is of type String.

getLocale()

Returns a Locale object, which shows where the request comes from.

getClientCertificateChain()

Returns a chain of the trusted client certificates as a Certificate[] array.

RSAContext

validatePasscode(passcode)

Validates the passcode and returns a String value showing if the user logon is successful. The returned value corresponds to one of the following:

  • rsaContext.VALID_PASSCODE

    The pascode is valid and the logon is successful.

  • rsaContext.INVALID_PASSCODE

    The passcode is not correct and the authentication failed.

  • rsaContext.VALID_NEXT_PASSCODE_REQUIRED

    The entered passcode is valid, but a second one is required for logon.

  • rsaContext.RSA_SERVICE_UNAVAILABLE

    The used RSA service is unavailable for passcode validation.

The passcode parameter is of type String.

validatePasscode(username, passcode)

Validates the username and passcode and returns a String value showing if the user logon is successful. The returned value corresponds to one of the following: rsaContext.VALID_PASSCODE, rsaContext.INVALID_PASSCODE, rsaContext.VALID_NEXT_PASSCODE_REQUIRED or rsaContext.RSA_SERVICE_UNAVAILABLE.

The username and passcode parameters are of type String.

setRADIUSDestination(destinationName)

Sets the name of an existing SLS destination of type RADIUS Destination. For more information, see Managing Destinations.

The destinationName parameter is of type String.

RADIUSContext

validatePasscode(passcode)

Validates the passcode and returns a String value showing if the user logon is successful. The returned value corresponds to one of the following:

  • radiusContext.VALID_PASSCODE

    The pascode is valid and the logon is successful.

  • radiusContext.INVALID_PASSCODE

    The passcode is not correct and the authentication failed.

  • radiusContext.VALID_NEXT_PASSCODE_REQUIRED

    The entered passcode is valid, but a second one is required for logon.

  • radiusContext.RSA_SERVICE_UNAVAILABLE

    The used RSA service is unavailable for passcode validation.

The passcode parameter is of type String.

validatePasscode(username, passcode)

Validates the username and passcode and returns a String value showing if the user logon is successful. The returned value corresponds to one of the following: radiusContext.VALID_PASSCODE, radiusContext.INVALID_PASSCODE, radiusContext.VALID_NEXT_PASSCODE_REQUIRED or radiusContext.RSA_SERVICE_UNAVAILABLE.

The username and passcode parameters are of type String.

setRADIUSDestination(destinationName)

Sets the name of an existing SLS destination of type RADIUS Destination. For more information, see Managing Destinations.

The destinationName parameter is of type String.

PasscodeValidationLoginResult

setValidationSuccessful()

The following methods define how the result is shown in the UI.

Sets the result of the validation as successful.

setValidationFailure()

Sets the result of the validation as not successful and no messages are shown to the user.

setValidationFailureWithErrorMessage(message)

Sets the result of the validation as not successful and an error message is shown to the user. The message parameter used for the error message is of type String.

setValidationFailureWithWarningMessage(message)

Sets the result of the validation as not successful and a warning message is shown to the user. The message parameter used for the warning message is of type String.

setValidationFailureWithInfoMessage(message)

Sets the result of the validation as not successful and an info message is shown to the user. The message parameter used for the info message is of type String.

LoginInfo

getUser()

Returns an IUser object containing information about the user.

Example
var loginInfo = context.getLoginInfo();
  var user = loginInfo.getUser();
  if (!user.isMemberOfGroup('GRUP.PRIVATE_DATASOURCE.un:Managers', true)) {
    result.doNotRequireSecondFactor();

getTOTPInfo()

Returns a TOTPInfo object.

Example
var loginInfo = context.getLoginInfo();
var totpInfo = loginInfo.getTOTPInfo();
	if (totpInfo.getStatus() == totpInfo.DISABLED){
	    ...
	}

getAuthenticationMethod()

Returns the used authentication method as String.

Possible returned values: password, client-cert, spnego, otp, password + otp, otp + password, otp + cookie, spnego + otp, unknown, unknown + otp, or others.

getPrincipal()

Returns a Principal object.

Example
var loginInfo = context.getLoginInfo();
var principal = loginInfo.getPrincipal();
    if (principal instanceof com.sap.engine.lib.security.ClientCertificatePrincipal) {
       result.doNotRequireSecondFactor();
    }

TOTPInfo

getStatus()

Returns a string signifying the status of the user account.

The status is equivalent to a value of one of the following constants: TOTPInfo.ENABLED, TOTPInfo.DISABLED, TOTPInfo.EXPIRED, TOTPInfo.SOON_TO_EXPIRE, TOTPInfo.LOCKED.

getPasscodeLength()

Returns the length of the current passcode as int.

getDigestAlgorithm()

Returns the digest algorithm as String used to generate the passcode.

The digest algorithm is equivalent to a value of one the following constants: TOTPInfo.SHA1, TOTPInfo.SHA256, TOTPInfo.SHA512.

getSecretKeyValidity()

Returns the validity in minutes of the time-based one-time password (TOTP) secret key as int, which specifies the user account validity.

getLockedPeriod()

Returns the period in minutes during which the passcode is locked. The returned value is int.