> ## Documentation Index
> Fetch the complete documentation index at: https://docs-staging-quickstart-revamp.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

> Learn about managing sessions with Actions

# Sessions with Actions

Using Sessions with [Actions](/docs/customize/actions) allows you to configure post-authentication risk detection and response capabilities to protect your applications and users against session hijacking. You can also dynamically customize the [session lifetime limits](/docs/manage-users/sessions/configure-session-lifetime-settings).

To facilitate this, post-login Actions feature two key objects:

* **event.session**: Provides relevant information including unique `id`, `created_at`, `expires_at`, `idle_expires_at`, `updated_at` dates, `clients`, `authentication_at`, and `device` information, such as `ASN`, `IP`, and `User_agent`.
* **api.session:** Allows you to manage existing sessions by revoking sessions or changing `expiry` dates.

The `event.session` and `api.session` objects both support interactive web-based flows, including [authorization code flow](/docs/get-started/authentication-and-authorization-flow/authorization-code-flow), implicit flow, device code flow, as well as <Tooltip tip="Security Assertion Markup Language (SAML): Standardized protocol allowing two parties to exchange authentication information without a password." cta="View Glossary" href="/docs/glossary?term=SAML">SAML</Tooltip> and <Tooltip tip="Security Assertion Markup Language (SAML): Standardized protocol allowing two parties to exchange authentication information without a password." cta="View Glossary" href="/docs/glossary?term=WS-Fed">WS-Fed</Tooltip>.

You can use the `event.session` object to review timestamps of the latest interactions and evaluate risks associated with the current transactions. You can also combine the `event.session` object with other event objects, such as `event.authentication` or `event.request`.

You can then use the `api.session` object to either reset the existing session expiry dates or revoke the session.

To learn more about these objects, review:

* [Event object](/docs/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-event-object): Learn about the session Event object and properties.
* [API object](/docs/customize/actions/explore-triggers/signup-and-login-triggers/login-trigger/post-login-api-object): Learn about the session API object and methods.

## Revoke sessions with Actions

The post-login **api.session.revoke(reason, options)** method allows you to react to risks associated with a transaction. This method includes an option to allow you to preserve the <Tooltip tip="Refresh Token: Token used to obtain a renewed Access Token without forcing users to log in again." cta="View Glossary" href="/docs/glossary?term=refresh+tokens">refresh tokens</Tooltip> bound to the revoked transaction.

In addition to revoking the session, the method will also initiate a `session-revoked` [OIDC Back-Channel Logout Initiator](/docs/authenticate/login/logout/back-channel-logout/oidc-back-channel-logout-initiators) to log out users from all applications bound to the current session and log a [session\_revoked](/docs/deploy-monitor/logs/log-event-type-codes) event in the tenant logs.

You can use this method to:

* Invalidate the current session transaction in Auth0
* Deny the current transaction
* Revoke all [refresh tokens](/docs/secure/tokens/refresh-tokens) associated with the existing session with a matching `session_id` value.

  * This is a customizable option; you can choose to preserve the refresh tokens rather than revoke them. This operation runs asynchronously and eventually becomes consistent.

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  If you want to use the `api.session.revoke(reason,options)` method, ensure that the property event.session.id exists.

  Different from `api.access.deny()`, `api.session.revoke()` will deny the current transaction and also revoke the session, therefore first factor authentication will be required again
</Callout>

### Monitor revoke log events

The revoke operation adds the following log event in your [tenant logs](/docs/deploy-monitor/logs):

A `session_revoked` event code indicating a revoked session with its associated `session_id` attribute.

## Change sessions expiry dates with Actions

You can modify session [expiry dates](/docs/manage-users/sessions/session-lifetime-limits) with the following post-login methods:

* **api.session.setExpiresAt(absolute)** allows you to define a new absolute (Require log in after) session expiration date for a specified session.
* **api.session.setIdleExpiresAt(idle)** allows you to set a new inactivity timeout date for a specified session.

You can use these methods to dynamically customize the session lifetime and inactivity policies based on:

* A user’s organization
* A user’s Auth0 connection
* A specific user’s group membership or profile
* Risk assessment
* Any other dynamic criteria available during the execution of the Action

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  If you want to use the `api.session.setExpiresAt(absolute)` and `api.session.setIdleExpiresAt(idle)` methods, ensure that a property of the event.session object exists, such as `event.session.id`.

  The `api.session.setIdleExpiresAt(idle)` method sets the session inactivity timeout for  the current interaction. If the method is not reapplied, subsequent successful interactions will override the inactivity timeout using the session inactivity timeout settings.
</Callout>

## Limitations

Sessions issued before the release of the post-login API methods `api.session.setExpiresAt(absolute)` and `api.session.setIdleExpiresAt(idle)` will not contain the following event.session property: `last_interacted_at.`

Sessions issued before the release of the post-login API method `api.session.revoke(reason, options)` will not contain the following event.session.device properties:

* `initial_ip`
* `initial_asn`
* `initial_user_agent`

For security reasons, inactivity and absolute timeouts cannot be set above the session settings defined in the [session lifetime limits](/docs/manage-users/sessions/configure-session-lifetime-settings) for the tenant. If you attempt to set a date above the lifetime limits, the API methods will update up to the lifetime limits and log a warning event (`w`) in the tenant logs.

## Use cases: Revoke a session

You can use [Actions](/docs/customize/actions) to configure risk detections and revoke risky sessions and their associated refresh tokens with the post-login `api.session.revoke(reason, options)` method and the `event.session` object.

### Revoke a session due to ASN network binding

You can use the post-login object properties, `event.session.device.initial_asn` and `event.request.asn` to bind session transactions to a specific [autonomous system number (ASN)](https://www.arin.net/resources/guide/asn/) network for their duration and require a re-authentication if the ASN network changes.

```js lines
exports.onExecutePostLogin = async (event, api) => {
  const sessionInitialAsn = event.session?.device?.initial_asn;
  const sessionCurrentAsn = event.request.asn;

  // if there is a session and the ASN changes
  if (
    sessionInitialAsn &&
    sessionCurrentAsn &&
    sessionInitialAsn != sessionCurrentAsn
  ) {
    api.session.revoke( "Invalid network change. Login again from a trusted network" )
  }
};
```

In this example, a check occurs at the start of the Action to verify that the `event.session.device.initial_asn` and `event.request.asn` properties remain within the same ASN network during the transaction. If this check fails, the Action calls  `api.session.revoke()` to:

* Invalidate the session
* Deny the current transaction
* Revoke all its associated refresh tokens
* Prompt for re-authentication

### Revoke a session due to an IP binding

You can use the post-login object properties `event.session.device.initial_ip` and `event.request.ip` to ensure a session transaction stays with the same IP address for its duration. In this scenario, any IP change is considered a risk, and the user will be prompted to re-authenticate.

```js lines
exports.onExecutePostLogin = async (event, api) => {
  const sessionInitialIp = event.session?.device?.initial_ip;
  const sessionCurrentIp = event.request.ip;

  // if there is a session and the IP changes
  if (
    sessionInitialIp &&
    sessionCurrentIp &&
    sessionInitialIp != sessionCurrentIp
  ) {
    api.session.revoke("Invalid IP change")
  }
};
```

In this example, a check occurs at the start of the Action to verify that the `event.session.device.initial_ip` and `event.request.ip` properties remain with the same IP address during the transaction. If the check fails, the Action then calls  `api.session.revoke()` to:

* Invalidate the session
* Deny the current transaction
* Revoke all its associated refresh tokens
* Prompt for re-authentication

## Use cases: Customize a session expiry dates

You can use [Actions](/docs/customize/actions) to customize session idle and absolute expiration dates. Specifically, you can configure the expiry dates for a particular session transaction using the post-login `api.session.setExpiresAt(absolute)` and `api.session.setIdleExpiresAt(idle)` methods and the `event.session` object.

### Customize absolute session expiration time based on connections

You can use the following post-login object properties, to define a lifetime for the connection used to authenticate a user.

* event.session.created\_at
* event.session.expires\_at

And using the Auth0 [Management API](https://auth0.com/docs/api/management/v2/connections/patch-connections-by-id) to create a connection metadata , `event.connection.metadata.session_timeout define` a specific connection timeout.

```js lines
exports.onExecutePostLogin = async (event, api) => {
  const created = Date.parse(event.session?.created_at ?? "");

  // desired session lifetime for this connection in milliseconds, configured as connection metadata
  const connection_lifetime = event.connection?.metadata?.session_timeout;

  // if there is a session lifetime defined for the connection, set it
  if (event.session?.id && connection_lifetime) {
    api.session.setExpiresAt(created + Number(connection_lifetime));
  }
};
```

In this example, a check occurs at the start of the Action to verify that there is a  `session_timeout` defined in the current connection. In that case, the Action sets the session expiration to be equal to when the session was `created` plus the `connection_lifetime`.

### Customize session inactivity timeout based on the Organization

You can define a `current_time` variable and using a new Organization metadata called `idle_session_timeout` set the idle timeout desired for an organization.

```js lines
exports.onExecutePostLogin = async (event, api) => {
  // The Organization metadata is configured with a shorter idle timeout for sessions (in milliseconds)
  const idle_organization_lifetime =
    event.organization?.metadata?.idle_session_timeout;

  // If the organization has an specific idle timeout defined, set the timeout
  if (event.session?.id && idle_organization_lifetime) {
    const current_time = new Date().getTime();

    api.session.setIdleExpiresAt(
      current_time + Number(idle_organization_lifetime),
    );
  }
};
```

In this example, if there is a specific idle timeout defined for the Organization, the Action sets the session inactivity timeout to be equal to the `current_time` plus the `idle_organization_lifetime` .
