# Manage Application Sessions in FusionAuth With Refresh Tokens

Learn how to track and revoke application sessions in FusionAuth by tying each session to a refresh token.

> For the index of this section of the site, see [llms.txt](https://fusionauth.io/docs/llms.txt)

A [centralized session](https://fusionauth.io/docs/concepts/glossary.md#centralized-session) ties each application session to a FusionAuth refresh token. Your application checks the refresh token on every request, so revoking the refresh token in FusionAuth ends the application session. To decide whether you need centralized sessions, see [Application Sessions](https://fusionauth.io/docs/authentication/sessions/how-sessions-work.md#application-sessions).

The following diagram shows a request after a user logs in. The only difference from an application-managed session is the check against FusionAuth:

```mermaid
sequenceDiagram
    participant Browser
    participant App as Application
    participant FusionAuth
    Browser ->> App : Request a page
    App ->> App : Read the refresh token Id from the session
    App ->> FusionAuth : Retrieve the refresh token
    alt Refresh token exists
        FusionAuth ->> App : 200
        App ->> Browser : Send the page
    else Refresh token revoked or expired
        FusionAuth ->> App : 404
        App ->> App : End the application session
        App ->> Browser : Redirect to login
    end
```

Each request checks the refresh token with FusionAuth.

## Prerequisites

*   An API key with `GET` and `DELETE` permissions on `/api/jwt/refresh`.
*   An application that logs users in with the [Authorization Code grant](https://fusionauth.io/docs/authentication/oauth/authorization-code.md) or the [Login API](https://fusionauth.io/docs/apis/login.md).

## Set Up Centralized Sessions

The first three steps set up login. The last two steps add a check to every request and a revoke to logout:

1.  ### Turn On Refresh Tokens
    
    For the hosted login pages, navigate to Applications -> Your Application -> OAuth . Turn on **Generate refresh tokens**, and select `Refresh Token` in **Enabled grants**.
    
    For the Login API, navigate to Applications -> Your Application -> Security . Turn on **Generate refresh tokens** and **Enable JWT refresh**.
    
    Click Save .
    
2.  ### Request a Refresh Token at Login
    
    When your application builds the authorization URL, include `offline_access` in the **`scope`** parameter: `scope=openid%20offline_access`. Without `offline_access`, FusionAuth doesn't issue a refresh token.
    
    The Login API returns a refresh token whenever the Application allows refresh tokens.
    
3.  ### Store the Refresh Token Id
    
    The token endpoint response includes **`refresh_token_id`**. Store the Id in your application session or in an [HttpOnly cookie](https://fusionauth.io/docs/authentication/sessions/cookies.md). Store the Id rather than the token value, because the Id stays the same when FusionAuth rotates a one-time use refresh token.
    
4.  ### Check the Refresh Token on Each Request
    
    Add middleware that retrieves the refresh token by Id with the [Retrieve Refresh Tokens API](https://fusionauth.io/docs/apis/jwt/retrieve-refresh-tokens.md). When FusionAuth returns an error, the session ended in FusionAuth, so end the application session. Skip the check for public routes such as login and the OAuth callback:
    
    Check the refresh token on each request
    
    ```js
    const alwaysAllowed = [ "/logout", "/login", "/favicon.ico", "/endsession","/" ];
    const alwaysAllowedPrefix = [ "/oauth-redirect", "/static" ];
    
    const {FusionAuthClient} = require('@fusionauth/typescript-client');
    
    const dotenv = require('dotenv');
    dotenv.config();
    
    const apiKey = process.env.apiKey;
    const fusionAuthURL = process.env.fusionAuthURL;
    const client = new FusionAuthClient(apiKey, fusionAuthURL);
    const refreshToken = 'refreshTokenCBF';
    
    /**
     * Redirect function
     * @param {import('express').Request} req - The request object
     * @param {import('express').Response} res - The response object
     * @param {import('express').NextFunction} next - The next middleware function
     */
    function redirectFunction(req, res, next) {
      if (alwaysAllowed.indexOf(req.originalUrl) > -1 ) {
        // always allow this
        next();
        return;
      }
    
      for (let i = 0; i < alwaysAllowedPrefix.length; i++) {
        let prefix = alwaysAllowedPrefix[i];
        if (req.originalUrl.startsWith(prefix)) {
          // always allow this
          next();
          return;
        }
      }
    
      const refreshTokenId = req.cookies[refreshToken];
      if (!refreshTokenId) {
        res.redirect(302, "/login");
        return;
      }
    
      client.retrieveRefreshTokenById(refreshTokenId)
        .then(() => next())
        // revoked or expired token: end the app session
        .catch(() => res.redirect(302, "/logout"));
    }
    
    module.exports = { redirectFunction };
    ```
    
    Retrieving a refresh token doesn't extend the refresh token's lifetime. When the Tenant uses a sliding window expiration policy and you want activity to keep the session alive, call the [Refresh Token grant](https://fusionauth.io/docs/authentication/oauth/refresh-token.md) instead, and discard the new access token. For the expiration policies, see [Session Settings](https://fusionauth.io/docs/authentication/sessions/session-settings.md#refresh-tokens).
    
5.  ### Revoke the Session on Logout
    
    When a user logs out, revoke the user's refresh tokens with the [Revoke Refresh Tokens API](https://fusionauth.io/docs/apis/jwt/revoke-refresh-tokens.md), then end the application session. The following route revokes every refresh token for the user, which also ends the [SSO session](https://fusionauth.io/docs/authentication/sessions/how-sessions-work.md#the-sso-session):
    
    Revoke all of the user's sessions on logout
    
    ```ts
    app.get('/endsession', async (req, res, next) => {
      console.log('Ending session...')
      const refreshTokenId = req.cookies[refreshToken];
    
      if (refreshTokenId) {
        try {
          const refreshTokenResponse = await client.retrieveRefreshTokenById(refreshTokenId);
          const responseJSON = refreshTokenResponse.response;
          if (responseJSON['refreshToken'] && responseJSON['refreshToken']['userId']) {
            const userId = responseJSON['refreshToken']['userId'];
            await client.revokeRefreshTokensByUserId(userId);
          }
        } catch(err) {
          console.log("in error");
          console.error(JSON.stringify(err));
        }
      }
    
      res.clearCookie(refreshToken);
      res.clearCookie(userSession);
      res.clearCookie(userToken);
      res.clearCookie(userDetails);
    
      res.redirect(302, '/')
    });
    ```
    
    To revoke a narrower set, such as the tokens for one Application, see [Revoke Sessions](https://fusionauth.io/docs/authentication/sessions/revoke-sessions.md#revoke-sessions).
    

## Log Out of One Device

To log the user out of the current device only, revoke the one refresh token by Id:

Revoke one session on logout

```ts
app.get('/endsession', async (req, res, next) => {
  console.log('Ending session...')
  const refreshTokenId = req.cookies[refreshToken];
  if (refreshTokenId) {
    try {
      await client.revokeRefreshTokenById(refreshTokenId);
    } catch(err) {
      console.log("in error");
      console.error(JSON.stringify(err));
    }
  }

  res.clearCookie(refreshToken);
  res.clearCookie(userSession);
  res.clearCookie(userToken);
  res.clearCookie(userDetails);

  // redirect back to changebank
  res.redirect(302, 'http://'+cbhostname+':'+cbport+'/account')
});
```

The SSO session survives a single revoke, so also redirect the browser to the [Logout endpoint](https://fusionauth.io/docs/apis/oauth/logout.md). Otherwise, FusionAuth logs the user back in on the next login redirect. For more information, see [Log Users Out](https://fusionauth.io/docs/authentication/sessions/log-users-out.md).

## Confirm the Result

1.  Log in to your application.
2.  In the Admin UI, navigate to Users -> The User -> Sessions . The new session appears in the list.
3.  Delete the session, then reload a page in your application. Your application sends you to the login page.

For a complete example with two applications, see the [example repository](https://github.com/FusionAuth/fusionauth-example-node-centralized-sessions).

Related

[Authentication How Sessions Work in FusionAuth Learn about the sessions that keep a user logged in to FusionAuth and to your applications, and how the sessions relate. sessionscentralized sessionsrefresh tokens](https://fusionauth.io/docs/authentication/sessions/how-sessions-work.md)

[Authentication Sessions, SSO, and Logout Learn about how FusionAuth keeps users logged in across applications, and how to configure session lifetimes, single sign-on, and logout. sessionslogoutrefresh tokens](https://fusionauth.io/docs/authentication/sessions.md)

[Authentication View and Revoke User Sessions Learn how to list a user's sessions and end the sessions from the Admin UI, the API, or automatically. sessionsrefresh tokenslogout](https://fusionauth.io/docs/authentication/sessions/revoke-sessions.md)

[Authentication How Logout Works in FusionAuth Learn about what each FusionAuth logout method ends, and how front-channel logout signs a user out of every application. logoutsessionsrefresh tokens](https://fusionauth.io/docs/authentication/sessions/how-logout-works.md)
---

## Other pages in Sessions

> For the full index of this section, see [Authentication](https://fusionauth.io/docs/llms-authentication.txt).

- [Configure Session and Token Lifetimes](https://fusionauth.io/docs/authentication/sessions/configure-session-lifetimes.md): Learn how to set how long users stay logged in to FusionAuth and to your applications.
- [Login Page Cookies](https://fusionauth.io/docs/authentication/sessions/cookies.md): Reference for the cookies that FusionAuth sets in the browser, including the SSO session cookie.
- [Enable SSO Across Applications](https://fusionauth.io/docs/authentication/sessions/enable-sso.md): Learn how to let users log in once and reach every application in a FusionAuth tenant without logging in again.
- [How Logout Works in FusionAuth](https://fusionauth.io/docs/authentication/sessions/how-logout-works.md): Learn about what each FusionAuth logout method ends, and how front-channel logout signs a user out of every application.
- [How Sessions Work in FusionAuth](https://fusionauth.io/docs/authentication/sessions/how-sessions-work.md): Learn about the sessions that keep a user logged in to FusionAuth and to your applications, and how the sessions relate.
- [Sessions, SSO, and Logout](https://fusionauth.io/docs/authentication/sessions.md): Learn about how FusionAuth keeps users logged in across applications, and how to configure session lifetimes, single sign-on, and logout.
- [Limit How Many Devices a User Can Log In From](https://fusionauth.io/docs/authentication/sessions/limit-concurrent-sessions.md): Learn how to cap the number of devices a user can stay logged in on at the same time.
- [Log Users Out of FusionAuth and Your Applications](https://fusionauth.io/docs/authentication/sessions/log-users-out.md): Learn how to log users out of one application or every application, and where to send users after logout.
- [View and Revoke User Sessions](https://fusionauth.io/docs/authentication/sessions/revoke-sessions.md): Learn how to list a user's sessions and end the sessions from the Admin UI, the API, or automatically.
- [Session and Token Lifetime Settings](https://fusionauth.io/docs/authentication/sessions/session-settings.md): Reference for every FusionAuth setting that controls session, token, and logout behavior.
- [Troubleshoot Sessions and Logout](https://fusionauth.io/docs/authentication/sessions/troubleshooting.md): Learn how to fix common problems with FusionAuth SSO, session lifetimes, and logout.
