Manage Application Sessions in FusionAuth With Refresh Tokens

On this page

A centralized sessionAn application session that your application ties to a FusionAuth refresh token, so you can view and revoke the session in FusionAuth. 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.

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

FusionAuthApplicationBrowserFusionAuthApplicationBrowseralt[Refresh tokenexists][Refresh tokenrevoked orexpired]Request a pageRead the refresh token Id from the sessionRetrieve the refresh token200Send the page404End the application sessionRedirect to login

Each request checks the refresh token with FusionAuth.

Prerequisites#

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 cookieA cookie that the browser sends with requests but hides from JavaScript, so a cross-site scripting attack can't read the cookie.. 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. 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
    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 instead, and discard the new access token. For the expiration policies, see Session Settings.

  5. Revoke the Session on Logout#

    When a user logs out, revoke the user's refresh tokens with the Revoke Refresh Tokens API, then end the application session. The following route revokes every refresh token for the user, which also ends the SSO sessionThe session FusionAuth keeps in the browser after a user logs in through the hosted login pages. While the SSO session lasts, FusionAuth logs the user in to other Applications in the Tenant without asking for credentials.:

    Revoke all of the user's sessions on logout
    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.

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
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. Otherwise, FusionAuth logs the user back in on the next login redirect. For more information, see Log Users Out.

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.