> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# API Object

> Learn about the post-login Action trigger's API object.

The API object for the post-login Actions trigger includes:

## `api.access`

Modify the access of the user that is logging in, such as rejecting the login attempt.

### `api.access.deny(reason)`

Mark the current login attempt as denied. This will prevent the end-user from completing
the login flow. This will *NOT* cancel other user-related side-effects (such as metadata
changes) requested by this Action. The login flow will immediately stop following the
completion of this action and no further Actions will be executed.

**Parameters**

**Parameters**

**reason** `string`

A human-readable explanation for rejecting the login. This may be presented
directly in end-user interfaces.

## `api.accessToken`

Request changes to the access token being issued.

### `api.accessToken.setCustomClaim(key, value)`

Set a custom claim on the Access Token that will be issued upon completion of the login flow.

**Parameters**

**Parameters**

**key** `string`

Name of the claim (note that this may need to be a fully-qualified url).

**value** `unknown`

The value of the claim.

### `api.accessToken.addScope(scope)`

Add a scope on the Access Token that will be issued upon completion of the login flow.

Restrictions: [Handling Scopes in Actions](https://auth0.com/docs/customize/actions/handling-scopes-in-actions).

**Parameters**

**Parameters**

**scope** `string`

The scope to be added.

### `api.accessToken.removeScope(scope)`

Remove a scope on the Access Token that will be issued upon completion of the login flow.

**Parameters**

**Parameters**

**scope** `string`

The scope to be removed.

## `api.authentication`

Request changes to the authentication state of the current user's session.

### `api.authentication.challengeWith(factor, options)`

Request a challenge for multifactor authentication using the supplied factor and optional additional factors.

When a multifactor challenge is requested, subsequent Actions will not be run until that challenge has been
fulfilled by the user. A user will have satisfied the challenge in any of the following situations:

1. They successfully complete the challenge for the default factor.
2. They successfully complete the challenge for any of the optional factors described in `additionalFactors`.

If any of the factors requested has already been challenged successfully in the current transaction, it will
be ignored.

If a factor is requested is not enabled on the tenant, it will be ignored. If a factor is requested that the user
has not enrolled, it will be ignored. If none of the requested factors is enabled or enrolled, the authentication
transaction will fail (i.e. login will not complete).

> [!NOTE]
>
> This method will result in a factor challenge screen being shown if the user has not already satisfied the requirements of the challenge. If `additionalFactors` are supplied, the user will have the option to select another factor if they choose to.

```js Challenge with a specific factor theme={null}
api.authentication.challengeWith({
  type: 'phone',
  options: { preferredMethod: 'both' }
});
```

```js Challenge with additional factors theme={null}
api.authentication.challengeWith({
  type: 'otp'
}, {
  additionalFactors: [{
    type: 'push-notification'
  }, {
    type: 'phone'
  }]
});
```

```js Challenge with push notification and disable OTP fallback theme={null}
api.authentication.challengeWith({
  type: 'push-notification',
  options: { otpFallback: false }
});
```

**Parameters**

**Parameters**

**factor** `factorselector`

An object describing the type of factor its options that should be used for the initial challenge.

**factor properties**

**type** `string`

A type of authentication factor such as `push-notification`, `phone`, `email`, `otp`, `webauthn-roaming`, `webauthn-platform`, and `recovery-code`.
Allowed values: `otp`, `email`, `webauthn-platform`, `webauthn-roaming`, `recovery-code`

**options** `dictionary`

Additional options for configuring a factor of a given type.
Optional.

**options** `challengewithoptions`

Additional options which can also specify `additionalFactors` as a property. Factor-specific options (for example `otpFallback` for `push-notification`) belong on `factor.options`.
Optional.

**options properties**

**additionalFactors** `array of objects`

Optional.

### `api.authentication.challengeWithAny(factors)`

Request a challenge for multifactor authentication using any of the supplied factors (showing a factor selection
screen first).

When a multifactor challenge is requested, subsequent Actions will not be run until that challenge has been
fulfilled by the user. A user will have satisfied the challenge in any of the following situations:

1. They successfully complete the challenge for any of the factors.

If any of the factors requested has already been challenged successfully in the current transaction, it will
be ignored.

If a factor is requested is not enabled on the tenant, it will be ignored. If a factor is requested that the user
has not enrolled, it will be ignored. If none of the requested factors is enabled or enrolled, the authentication
transaction will fail (i.e. login will not complete).

> [!NOTE]
>
> This method will result in the factor selector screen being shown if the user has not already satisfied the requirements of the challenge. If there is a preferred factor, the `api.authentication.challengeWith()` method is preferred. The factor selector screen will not be shown if only one factor is passed in or is valid.

**Parameters**

**Parameters**

**factors** `array of objects`

An array of factors.

### `api.authentication.enrollWith(factor, options)`

Request an enrollment for multifactor authentication using the supplied factor and optional additional factors.

When a multifactor enrollment is requested, subsequent Actions will not be run until that enrollment has been
fulfilled by the user.

If any of the factors requested has already been enrolled or challenged successfully in the current transaction, it will
be ignored.

If a factor that is not enabled in the tenant is requested, it will be ignored.
If a factor that the user has already enrolled is requested, it will be ignored.
If none of the requested factors is enabled and not enrolled, the authentication
transaction will fail (i.e. login will not complete).

```js Enroll with additional factors theme={null}
api.authentication.enrollWith({
  type: 'otp'
}, {
  additionalFactors: [{
    type: 'push-notification'
  }, {
    type: 'phone'
  }]
});
```

**Parameters**

**Parameters**

**factor** `enrollmentfactorselector`

An object describing the type of factor that should be used for the initial enrollment prompts and its options.

**factor properties**

**type** `string`

A type of authentication factor such as `push-notification`, `phone`, `otp`, `webauthn-roaming`, `webauthn-platform`, and `recovery-code`.
Allowed values: `otp`, `webauthn-platform`, `webauthn-roaming`, `recovery-code`, `push`, `push-notification`

**options** `dictionary`

Additional options for configuring a factor of a given type.
Optional.

**options** `enrollwithoptions`

Additional options which can also specify `additionalFactors` as a property.
Optional.

**options properties**

**additionalFactors** `array of objects`

Optional.

### `api.authentication.enrollWithAny(factors)`

Request an enrollment for multifactor authentication using any of the supplied factors (showing a factor selection
screen first).

When a multifactor enrollment is requested, subsequent Actions will not be run until that enrollment has been
fulfilled by the user.

If any of the factors requested has already been enrolled successfully in the current transaction, it will
be ignored.

If a factor that is not enabled in the tenant is requested, it will be ignored.
If a factor that the user has already enrolled is requested, it will be ignored.
If none of the requested factors is enabled and not enrolled, the authentication
transaction will fail (i.e. login will not complete).

> [!NOTE]
>
> If there is a preferred factor, the `api.authentication.enrollWith()` method is preferred. The factor selector screen will not be shown if only one factor is passed in or is valid.

**Parameters**

**Parameters**

**factors** `array of objects`

An array of additional factors.

### `api.authentication.recordMethod(provider_url)`

Indicate that a custom authentication method has been completed in the current
session. This method will then be available in the `event.authentication.methods`
array in subsequent logins.

**IMPORTANT**: This API is only available from within the `onContinuePostLogin`
function for `PostLogin` Actions. In other words, this may be used to record the
completion of a custom authentication method after redirecting the user via
`api.redirect.sendUserTo()`.

**Parameters**

**Parameters**

**provider\_url** `string`

An `http:` or `https:` URL that uniquely represents the completed
authentication method.

### `api.authentication.setPrimaryUser(primary_user_id)`

Change the primary user for the login transaction.

In scenarios that require linking users, the user identity used to initiate the login may no longer
exist as a discrete user. That identity may now be a secondary identity of an existing user. In
such situations, the `setPrimaryUser()` function can be used to indicate that the subject of the
login should be changed.

**IMPORTANT**: Insecurely linking accounts can allow malicious actors to access legitimate
user accounts.

**IMPORTANT**: The identity used to authenticate the login *must* be among the secondary identities
of the user referenced by `primary_user_id`. The login will fail and tokens will not be issued
otherwise.

**Parameters**

**Parameters**

**primary\_user\_id** `string`

The user ID of the user for whom tokens should be issued (the `sub` claim).

## `api.idToken`

Request changes to the ID token being issued.

### `api.idToken.setCustomClaim(key, value)`

Set a custom claim on the ID Token that will be issued upon completion of the login flow.

**Parameters**

**Parameters**

**key** `string`

Name of the claim (note that this may need to be a fully-qualified url).

**value** `unknown`

The value of the claim.

## `api.multifactor`

Set or remove the requirement for multifactor authentication on the login attempt.

### `api.multifactor.enable(provider, options)`

Enable multifactor authentication for this login flow. When enabled, users must complete the
configured multifactor challenge. The actual multifactor challenge will be deferred to the
end of the login flow.

**Parameters**

**Parameters**

**provider** `string`

The name of the multifactor provider to use or the value `"any"` to use any
of the configured providers.
Allowed values: `none`, `guardian`, `google-authenticator`, `duo`, `any`

**options** `enablemultifactoroptions`

Additional options for enabling multifactor challenges.
Optional.

**options properties**

**allowRememberBrowser** `boolean`

When provider is set to `google-authenticator` or `duo`, the user is prompted for MFA once
every 30 days. When provider is set to `guardian`, the MFA prompt displays the enrollment
checkbox for users to choose whether or not to enroll. Defaults to `false`. To learn more,
read [Customize Multi-Factor Authentication Pages](https://auth0.com/docs/secure/multi-factor-authentication/customize-mfa).
Optional.

**providerOptions** `object`

Additional options to configure the challenge, only available for the `duo` provider.
Optional.

**providerOptions properties**

**host** `string`

This is the API hostname value from your Duo account.

**ikey** `string`

This is the Client ID (previously Integration key) value from your Duo account.

**skey** `string`

This is the Client secret (previously Secret key) value from your Duo account.

**username** `string`

Use some attribute of the profile as the username in DuoSecurity. This is also useful if you already have your users enrolled in Duo.
Optional.

## `api.redirect`

Configure and initiate external redirects.

### `api.redirect.encodeToken(options)`

Create a session token suitable for using as a query string parameter redirect target (via `sendUserTo`)
that contains data whose authenticity must be provable by the target endpoint. The target endpoint
can verify the authenticity and integrity of the data by checking the JWT's signature
using a shared secret.

The shared secret should be stored as a **secret** of the Action and will be readable at
`event.secrets['<secret_name>']`.

**Parameters**

**Parameters**

**options** `tokencreationoptions`

Configure how sensitive data is encoded into the query parameters of the
resulting url.

**options properties**

**expiresInSeconds** `number`

Number of seconds before this token will expire
Optional.

**payload** `dictionary`

The data intended to be passed to the target of the redirect and whose authenticity
and integrity must be provable.

**secret** `string`

A secret that will be used to sign a JWT that is shared with the redirect target. The
secret value should be stored as a **secret** and retrieved using
`event.secrets['<secret_name>']`.

### `api.redirect.sendUserTo(url, options)`

Cause the login pipeline to trigger a browser redirect to the target `url` immediately after
this action completes. The `createUrl` helper method is provided to simplify encoding
data as a query parameter in the target `url` such that the data's authenticity and
integrity can be verified by the target endpoint.

**Parameters**

**Parameters**

**url** `string`

**options** `sendusertooptions`

Optional.

**options properties**

**query** `dictionary`

An object representing additional query string parameters that should be appended to
the redirect URL.
Optional.

### `api.redirect.canRedirect()`

Indicates if the current transaction is eligibile for a user redirect. Certain protocols such
as `oauth2-resource-owner`, `oauth2-refresh-token` do not support
redirecting the user. A request with `prompt=none` is also not eligible for a redirect.

### `api.redirect.validateToken(options)`

Retrieve the data encoded in a JWT token passed to the `/continue` endpoint while verifying
the authenticity and integrity of that data.

**Parameters**

**Parameters**

**options** `validatesessiontokenoptions`

Options for retrieving the data encoded in a JWT token passed to the
`/continue` endpoint following a rediret.

**options properties**

**secret** `string`

**tokenParameterName** `string`

The name of the query or body parameter that was sent to the /continue endpoint.
Optional.

## `api.user`

Make changes to the metadata of the user that is logging in.

### `api.user.setAppMetadata(key, value)`

Set application-specific metadata for the user that is logging in.

Note: This method should not be used in callbacks. Invoking this method won't update the metadata immediately.
You can call this several times throughout multiple actions of the same flow and the engine will aggregate the
changes and update the metadata at once before the flow is completed. This function works only with metadata that
are in the object format.

**Parameters**

**Parameters**

**key** `string`

The metadata property to be set.

**value** `unknown`

The value of the metadata property. This may be set to `null` to remove the
metadata property.

### `api.user.setUserMetadata(key, value)`

Set general metadata for the user that is logging in.

Note: This method should not be used in callbacks. Invoking this method won't update the metadata immediately.
You can call this several times throughout multiple actions of the same flow and the engine will aggregate the
changes and update the metadata at once before the flow is completed. This function works only with metadata that
are in the object format.

**Parameters**

**Parameters**

**key** `string`

The metadata property to be set.

**value** `unknown`

The value of the metadata property. This may be set to `null` to remove the
metadata property.

## `api.cache`

Make changes to the cache.

### `api.cache.delete(key)`

Delete a record describing a cached value at the supplied
key if it exists.

**Parameters**

**Parameters**

**key** `string`

The key of the cache record to delete.

### `api.cache.get(key)`

Retrieve a record describing a cached value at the supplied key,
if it exists. If a record is found, the cached value can be found
at the `value` property of the returned object.

**Parameters**

**Parameters**

**key** `string`

The key of the record stored in the cache.

### `api.cache.set(key, value, options)`

Store or update a string value in the cache at the specified key.

Values stored in this cache are scoped to the Trigger in which they
are set. They are subject to the [Actions Cache Limits](https://auth0.com/docs/customize/actions/limitations).

Values stored in this way will have lifetimes of *up to* the specified
`ttl` or `expires_at` values. If no lifetime is specified, a default of
lifetime of 15 minutes will be used. Lifetimes may not exceed the maximum
duration listed at [Actions Cache Limits](https://auth0.com/docs/customize/actions/limitations).

**Important**: This cache is designed for short-lived, ephemeral data. Items may not be
available in later transactions even if they are within their supplied their lifetime.

**Parameters**

**Parameters**

**key** `string`

The key of the record to be stored.

**value** `string`

The value of the record to be stored.

**options** `cachesetoptions`

Options for adjusting cache behavior.
Optional.

**options properties**

**expires\_at** `number`

The absolute expiry time in milliseconds since the unix epoch.
While cached records may be evicted earlier, they will
never remain beyond the supplied `expires_at`.

*Note*: This value should not be supplied if a value was also
provided for `ttl`. If both options are supplied, the
earlier expiry of the two will be used.
Optional.

**ttl** `number`

The time-to-live value of this cache entry in milliseconds.
While cached values may be evicted earlier, they will
never remain beyond the supplied `ttl`.

*Note*: This value should not be supplied if a value was also
provided for `expires_at`. If both options are supplied, the
earlier expiry of the two will be used.
Optional.

## `api.samlResponse`

Configure custom SAML configurations and attributes.

### `api.samlResponse.setAttribute(attribute, value)`

Set attributes on the SAML assertion being issued to the authenticated user.

**Parameters**

**Parameters**

**attribute** `string`

The SAML attribute to be set.

**value** `object`

The value of the SAML claim. Setting this value to `null` or
`undefined` will remove the claim from the assertion.

### `api.samlResponse.setAudience(audience)`

Audience of the SAML assertion.
Default is issuer on SAMLRequest.

**Parameters**

**Parameters**

**audience** `string`

### `api.samlResponse.setRecipient(recipient)`

Recipient of the SAML assertion (SubjectConfirmationData).
Default is AssertionConsumerUrl on SAMLRequest or callback URL if no SAMLRequest was sent.

**Parameters**

**Parameters**

**recipient** `string`

### `api.samlResponse.setCreateUpnClaim(createUpnClaim)`

Whether or not a UPN claim should be created. Default is true.

**Parameters**

**Parameters**

**createUpnClaim** `boolean`

### `api.samlResponse.setPassthroughClaimsWithNoMapping(passthroughClaimsWithNoMapping)`

If true (default), for each claim that is not mapped to the common profile, Auth0 passes through those in the output assertion.
If false, those claims won't be mapped.

**Parameters**

**Parameters**

**passthroughClaimsWithNoMapping** `boolean`

### `api.samlResponse.setMapUnknownClaimsAsIs(mapUnknownClaimsAsIs)`

If passthroughClaimsWithNoMapping is true and this is false (default), for each claim not mapped to the common profile Auth0 adds a prefix `http://schema.auth0.com`.
If true it will pass through the claim as-is.

**Parameters**

**Parameters**

**mapUnknownClaimsAsIs** `boolean`

### `api.samlResponse.setMapIdentities(mapIdentities)`

If true (default), it adds more information in the token such as the provider (Google, ADFS, AD, etc.) and the access token, if available.

**Parameters**

**Parameters**

**mapIdentities** `boolean`

### `api.samlResponse.setSignatureAlgorithm(signatureAlgorithm)`

Signature algorithm to sign the SAML assertion or response.
Default is rsa-sha256.

**Parameters**

**Parameters**

**signatureAlgorithm** `string`

Allowed values: `rsa-sha256`

### `api.samlResponse.setSignatureAlgorithm(signatureAlgorithm)`

**Parameters**

**Parameters**

**signatureAlgorithm** `string`

Allowed values: `rsa-sha1`

### `api.samlResponse.setDigestAlgorithm(digestAlgorithm)`

Digest algorithm to calculate digest of the SAML assertion or response.
Default is sha256.

**Parameters**

**Parameters**

**digestAlgorithm** `string`

Allowed values: `sha256`

### `api.samlResponse.setDigestAlgorithm(digestAlgorithm)`

**Parameters**

**Parameters**

**digestAlgorithm** `string`

Allowed values: `sha1`

### `api.samlResponse.setDestination(destination)`

Destination of the SAML response. If not specified, it will be AssertionConsumerUrl of SAMLRequest or callback URL if there was no SAMLRequest.

**Parameters**

**Parameters**

**destination** `string`

### `api.samlResponse.setLifetimeInSeconds(lifetimeInSeconds)`

Expiration of the token.
Default is 3600 seconds (1 hour).

**Parameters**

**Parameters**

**lifetimeInSeconds** `number`

### `api.samlResponse.setSignResponse(signResponse)`

Whether or not the SAML response should be signed.
By default the SAML assertion will be signed, but not the SAML response.
If true, SAML Response will be signed instead of SAML assertion.
Default to false.

**Parameters**

**Parameters**

**signResponse** `boolean`

### `api.samlResponse.setNameIdentifierFormat(nameIdentifierFormat)`

Default is urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified.

**Parameters**

**Parameters**

**nameIdentifierFormat** `string`

### `api.samlResponse.setNameIdentifierProbes(nameIdentifierProbes)`

Auth0 will try each of the attributes of this array in order.
If one of them has a value, it will use that for the Subject/NameID.

The order is:

* [http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier](http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier) (mapped from user\_id),
* [http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress](http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress) (mapped from email),
* [http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name](http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name) (mapped from name).

**Parameters**

**Parameters**

**nameIdentifierProbes** `array of string`

### `api.samlResponse.setAuthnContextClassRef(authnContextClassRef)`

Default is urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified.

**Parameters**

**Parameters**

**authnContextClassRef** `string`

### `api.samlResponse.setSigningCert(signingCert)`

Optionally indicates the public key certificate used to validate SAML requests.
If set, SAML requests will be required to be signed.
A sample value would be "-----BEGIN CERTIFICATE-----\nMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV\n\[..all the other lines..]-----END CERTIFICATE-----\n".

**Parameters**

**Parameters**

**signingCert** `string`

### `api.samlResponse.setIncludeAttributeNameFormat(includeAttributeNameFormat)`

When set to true, we infer the NameFormat based on the attribute name. NameFormat values are urn:oasis:names:tc:SAML:2.0:attrname-format:uri, urn:oasis:names:tc:SAML:2.0:attrname-format:basic and urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified.
If set to false, the attribute NameFormat is not set in the assertion.
Default is true.

**Parameters**

**Parameters**

**includeAttributeNameFormat** `boolean`

### `api.samlResponse.setTypedAttributes(typedAttributes)`

When set to true, we infer the xs:type of the element. Types are xs:string, xs:boolean, xs:double and xs:anyType.
When set to false all xs:type are xs:anyType.
Default is true.

**Parameters**

**Parameters**

**typedAttributes** `boolean`

### `api.samlResponse.setEncryptionCert(encryptionCert)`

Optionally specify a certificate used to encrypt the SAML assertion.
The certificate should be obtained from the service provider.
Both the certificate and public key must be specified.
A sample value would be "-----BEGIN CERTIFICATE-----\nMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV\n\[..all the other lines..]-----END CERTIFICATE-----\n".

**Parameters**

**Parameters**

**encryptionCert** `string`

### `api.samlResponse.setEncryptionPublicKey(encryptionPublicKey)`

Optionally specify a public key used to encrypt the SAML assertion.
The public key should be obtained from the service provider.
Both the public key and certificate must be specified.
A sample value would be "-----BEGIN PUBLIC KEY-----\nnMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV\n\[..all the other lines..]-----END PUBLIC KEY-----\n".

**Parameters**

**Parameters**

**encryptionPublicKey** `string`

### `api.samlResponse.setCert(cert)`

By default, Auth0 will use the private/public key pair assigned to your tenant to sign SAML responses or assertions.
For very specific scenarios, you might wish to provide your own certificate and private key.

Both the certificate and private key must be specified.
A sample value would be "-----BEGIN CERTIFICATE-----\nMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV\n\[..all the other lines..]-----END CERTIFICATE-----\n".

**Parameters**

**Parameters**

**cert** `string`

### `api.samlResponse.setKey(key)`

By default, Auth0 will use the private/public key pair assigned to your tenant to sign SAML responses or assertions.
For very specific scenarios, you might wish to provide your own certificate and private key.

Since this private key is sensitive, **we recommend using the Add Secret functionality of Actions**.
See here for more details: [https://auth0.com/docs/customize/actions/write-your-first-action#add-a-secret](https://auth0.com/docs/customize/actions/write-your-first-action#add-a-secret)

Both the certificate and private key must be specified.
A sample value would be "-----BEGIN PRIVATE KEY-----\nnMIIC8jCCAdqgAwIBAgIJObB6jmhG0QIEMA0GCSqGSIb3DQEBBQUAMCAxHjAcBgNV\n\[..all the other lines..]-----END PRIVATE KEY-----\n".

**Parameters**

**Parameters**

**key** `string`

### `api.samlResponse.setRelayState(relayState)`

Optionally specify a RelayState used to return to service provider

**Parameters**

**Parameters**

**relayState** `string`

### `api.samlResponse.setIssuer(issuer)`

Optionally specify the issuer of the SAML assertion.
Default is urn:auth0:TENANT

**Parameters**

**Parameters**

**issuer** `string`

### `api.samlResponse.setEncryptionAlgorithm(encryptionAlgorithm)`

Set encryption algorithm for SAML assertion.
Default is aes256-cbc.

```js Set the encryption algorithm to aes256-gcm (recommended) theme={null}
api.samlResponse.setEncryptionAlgorithm('aes256-gcm');
```

**Parameters**

**Parameters**

**encryptionAlgorithm** `string`

* The algorithm to use (aes256-gcm is recommended)
  Allowed values: `aes256-gcm`

### `api.samlResponse.setEncryptionAlgorithm(encryptionAlgorithm)`

```js Set encryption algorithm to aes256-cbc (not recommended) theme={null}
api.samlResponse.setEncryptionAlgorithm('aes256-cbc');
```

**Parameters**

**Parameters**

**encryptionAlgorithm** `string`

* The algorithm to use (aes256-cbc is deprecated)
  Allowed values: `aes256-cbc`

## `api.validation`

Prevent user from logging in by throwing a validation error.

### `api.validation.error(errorCode, errorMessage)`

Throw an error when there is a validation error.

**Parameters**

**Parameters**

**errorCode** `string`

A customer defined error code for the validation error.

**errorMessage** `string`

A customer defined message for the validation error.

## `api.rules`

Identify if a rule has been executed in the current transaction.

### `api.rules.wasExecuted(ruleId)`

Check whether a Rule with a specific ID has been executed in the current transaction.

**Parameters**

**Parameters**

**ruleId** `string`

The Rule ID.

## `api.prompt`

Renders a custom prompt.

### `api.prompt.render(promptId, promptOptions)`

Renders a custom prompt.

**Parameters**

**Parameters**

**promptId** `string`

The prompt ID.

**promptOptions** `promptoptions`

The render options.
Optional.

**promptOptions properties**

**fields** `dictionary`

Key-value pairs to populate field values (client-side).
Optional.

**vars** `dictionary`

Key-value pairs to inject variables (server-side).
Optional.

## `api.refreshToken`

Request changes to the current user's refresh token.

### `api.refreshToken.revoke(reason)`

\[Enterprise Customers] Revoke the current user refresh token and mark the current refresh token exchange attempt as denied. This will prevent
the end-user from completing the refresh token exchange flow and revoke the currently used refresh token.
The refresh token exchange flow will immediately stop following the completion of this action and no further Actions will be executed.

This method can be used only during Refresh Token Exchange flow, when `event.transaction.protocol === "oauth2-refresh-token"`.

**Parameters**

**Parameters**

**reason** `string`

A human-readable explanation for rejecting the refresh token exchange. This may be presented
directly in end-user interfaces.

### `api.refreshToken.setExpiresAt(absolute)`

\[Enterprise Customers] Sets a new absolute expiration time for the current refresh token.
The expiration cannot be set higher than the maximum refresh token lifetime set in the settings.
When called multiple times, the earliest expiration time will be used.

**Parameters**

**Parameters**

**absolute** `number`

Required, the new absolute expiration time in milliseconds since the unix epoch, after which the Refresh Token will be considered invalid.

### `api.refreshToken.setIdleExpiresAt(inactivity)`

\[Enterprise Customers] Sets a new idle expiration time for the current refresh token.
The expiration cannot be set higher than the maximum absolute refresh token lifetime set in the settings.
When called multiple times, the earliest expiration time will be used.

**Parameters**

**Parameters**

**inactivity** `number`

Required, the new idle inactivity time in milliseconds since the unix epoch, after which the Refresh Token will be considered invalid
if it is not used during this period.

### `api.refreshToken.setMetadata(key, value)`

Sets a key value pair in the metadata object of the current refresh token.

**Parameters**

**Parameters**

**key** `string`

Required, the key to set in the metadata object.

**value** `string`

Required, the value to set for the key in the metadata object, null values will delete the provided metadata key.

### `api.refreshToken.deleteMetadata(key)`

Deletes a key in the metadata object of the current refresh token.

**Parameters**

**Parameters**

**key** `string`

Required, the key to delete from the metadata object.

### `api.refreshToken.evictMetadata()`

Deletes all keys from the metadata object of the current refresh token.

## `api.session`

Request changes to the current user's session.

### `api.session.revoke(reason, options)`

\[Enterprise Customers] Revoke the current user session and mark the current login attempt as denied. This will prevent
the end-user from completing the login flow and revoke their session. The login flow will immediately
stop following the completion of this action and no further Actions will be executed.

```js Revoke the session while preserving refresh tokens theme={null}
api.session.revoke('reason', { preserveRefreshTokens: true });
```

**Parameters**

**Parameters**

**reason** `string`

A human-readable explanation for rejecting the login. This may be presented
directly in end-user interfaces.

**options** `sessionrevocationoptions`

Optional.

**options properties**

**preserveRefreshTokens** `boolean`

Default to false. If true, the system ends the session and keeps the refresh tokens. The application may continue to get access tokens for the duration of the refresh token lifetime.
Optional.

### `api.session.setExpiresAt(absolute)`

\[Enterprise Customers] Sets a new absolute expiration time for the current session.
The expiration cannot be set higher than the maximum session lifetime set in the tenant settings.
When called multiple times, the earliest expiration time will be used.

**Parameters**

**Parameters**

**absolute** `number`

Required, the new absolute expiration time in milliseconds since the unix epoch, after which the Session will be considered invalid.

### `api.session.setIdleExpiresAt(inactivity)`

\[Enterprise Customers] Sets a new idle expiration time for the current session.
The expiration cannot be set higher than the maximum absolute session lifetime set in the tenant settings.
When called multiple times, the earliest expiration time will be used.

**Parameters**

**Parameters**

**inactivity** `number`

Required, the new inactivity expiration time in milliseconds since the unix epoch, after which the Session will be considered invalid if there
is no user interaction during this period.

### `api.session.setCookieMode(mode)`

\[Enterprise Customers] \[Early Access] Sets the cookie mode for the current session, allowing it to be either 'persistent' or 'non-persistent' (ephemeral).
This determines how the session cookie is handled in the browser:

* 'persistent': The cookie will be stored until it expires or is deleted by the user.
* 'non-persistent' (ephemeral): The cookie will be deleted when the browser is closed.

If multiple setCookieMode invocations are made, only the last one will take effect. In case 'non-persistent' is set, the cookie will be deleted when the browser is closed, however, the session itself will remain valid until its absolute or idle expiration time is reached
or the session is revoked through our available APIs. For more information on cookie modes, please refer to our documentation.

**Parameters**

**Parameters**

**mode** `string`

Required, the cookie mode for the current session.
Can be either 'persistent' or 'non-persistent' (ephemeral).
Allowed values: `persistent`, `non-persistent`

### `api.session.setMetadata(key, value)`

\[Enterprise Customers] \[Early Access] Sets a key value pair in the metadata object of the current session.

**Parameters**

**Parameters**

**key** `string`

Required, the key to set in the metadata object.

**value** `string`

Required, the value to set for the key in the metadata object, null values will delete the provided metadata key.

### `api.session.deleteMetadata(key)`

\[Enterprise Customers] \[Early Access] Deletes a key in the metadata object of the current session.

**Parameters**

**Parameters**

**key** `string`

Required, the key to delete from the metadata object.

### `api.session.evictMetadata()`

\[Enterprise Customers] \[Early Access] Deletes all keys from the metadata object of the current session.

## `api.transaction`

Make changes to the transaction.

### `api.transaction.setMetadata(key, value)`

Store or update the value in the transaction metadata for a specified key.

Metadata modified using this method is updated in real-time in the
`event.transaction.metadata` object.

**Parameters**

**Parameters**

**key** `string`

The key of the property to be set.

**value** `object`

The value of the property. This may be set to `null` to remove the
metadata property.

### `api.transaction.addTargetScope(scope)`

Add a scope to the target scope set. After all Actions complete, added scopes are
evaluated against the transaction's applicable authorization policies, including App
Access Permissions and RBAC. Unauthorized scopes are silently dropped. Authorized
additions are included in the consent prompt when explicit user consent is required.

Scopes modified using this method are updated in real-time in the
`event.transaction.target_scopes` array.

```js theme={null}
exports.onExecutePostLogin = async (event, api) => {
  api.transaction.addTargetScope('read:reports');
};
```

**Parameters**

**Parameters**

**scope** `string`

The scope to add.

### `api.transaction.removeTargetScope(scope)`

Remove a scope from the target scope set.

Scopes modified using this method are updated in real-time in the
`event.transaction.target_scopes` array.

```js theme={null}
exports.onExecutePostLogin = async (event, api) => {
  api.transaction.removeTargetScope('admin:full');
};
```

**Parameters**

**Parameters**

**scope** `string`

The scope to remove.

### `api.transaction.setTargetScopes(scopes)`

Replace the entire target scope set. After all Actions complete, the new scopes are
evaluated against the transaction's applicable authorization policies, including App
Access Permissions and RBAC. Unauthorized scopes are silently dropped. All scopes
remaining after filtering are included in the consent prompt when explicit user
consent is required.

Scopes modified using this method are updated in real-time in the
`event.transaction.target_scopes` array.

```js theme={null}
exports.onExecutePostLogin = async (event, api) => {
  api.transaction.setTargetScopes(['read:users', 'write:users']);
};
```

**Parameters**

**Parameters**

**scopes** `array of string`

The new target scope set.

### `api.transaction.clearTargetScopes()`

Remove all scopes from the target scope set.

Scopes modified using this method are updated in real-time in the
`event.transaction.target_scopes` array.

```js theme={null}
exports.onExecutePostLogin = async (event, api) => {
  api.transaction.clearTargetScopes();
};
```

## `api.groups`

Get information about user groups membership.

### `api.groups.getUserGroups(params)`

Get the paginated list of the groups the user belongs to.

**Parameters**

**Parameters**

**params** `getusergroupsparams`

* An object containing pagination options.
  Optional.

**params properties**

**take** `number`

Optional.

**from** `string`

Optional.

### `api.groups.hasGroupMembership(groups)`

Checks if the user is a member of any of the specified groups and provides details
about the matching groups if the user is a member.

**Parameters**

**Parameters**

**groups** `array of string`

* An array of group identifiers (IDs or names) to check membership against.

## `api.roles`

Get information about user roles assignments.

### `api.roles.getUserEffectiveRoles(params)`

Returns all roles assigned to a user, directly or through group membership,
optionally scoped to an organization, using checkpoint pagination.

```js Fetch the first page of roles theme={null}
const result = await api.roles.getUserEffectiveRoles({ take: 50 });
console.log(result.roles);
```

```js Paginate through roles theme={null}
let cursor;
do {
  const result = await api.roles.getUserEffectiveRoles({ take: 100, from: cursor });
  console.log(result.roles);
  cursor = result.next;
} while (cursor);
```

**Parameters**

**Parameters**

**params** `getusereffectiverolesparams`

* Checkpoint pagination parameters.
  Optional.

**params properties**

**take** `number`

The maximum number of roles to return (up to 100).
Optional.

**from** `string`

Pagination token from the previous response's `next` field. Use this to retrieve the next page of results.
Optional.

### `api.roles.getUserEffectiveRolesByIds(ids)`

Returns roles assigned to a user, directly or through group membership,
optionally scoped to an organization, filtered by role IDs.

```js Filter roles by specific IDs theme={null}
const result = await api.roles.getUserEffectiveRolesByIds([
  'rol_1234567890',
  'rol_0987654321'
]);
console.log(result.roles);
```

**Parameters**

**Parameters**

**ids** `array of string`

* Array of role IDs to filter by (up to 100).

### `api.roles.getUserEffectiveRolesByNames(names)`

Returns roles assigned to a user, directly or through group membership,
optionally scoped to an organization, filtered by role names.

```js Filter roles by specific names theme={null}
const result = await api.roles.getUserEffectiveRolesByNames([
  'Admin',
  'Editor'
]);
console.log(result.roles);
```

**Parameters**

**Parameters**

**names** `array of string`

* Array of role names to filter by (up to 50).
