Enhance Auth Endpoints To Manage CSRF Tokens

Update your Callback and Logout endpoints to create and clean up CSRF tokens.

Now that your CSRF middleware is set up to verify CSRF tokens, we need to update your Callback Endpoint and Logout Endpoint to create and clean up CSRF tokens.


Update Callback Endpoint

Your Callback Endpoint needs to be updated to create a CSRF token. The CSRF token will be derived from a session-specific CSRF secret. Once the CSRF token is generated, it will be stored in a cookie so that the frontend JavaScript code can read it. In addition, the CSRF secret will be stored in the session cookie so the CSRF middleware can access it to verify the CSRF token.

// Callback endpoint
app.get('/auth/callback', async (req, res, next) => {
  try {
    const callbackResult = await wristbandAuth.callback(req, res);
    const { callbackData, result } = callbackResult;

    if (result === CallbackResultType.REDIRECT_REQUIRED) {
      return;
    }

    req.session.isAuthenticated = true;
    req.session.accessToken = callbackData.accessToken;
    req.session.expiresAt = Date.now() + callbackData.expiresIn * 1000;
    req.session.refreshToken = callbackData.refreshToken;
    req.session.userId = callbackData.userinfo.sub;
    req.session.tenantId = callbackData.userinfo.tnt_id;
    req.session.tenantDomainName = callbackData.tenantDomainName;
    req.session.tenantCustomDomain = callbackData.tenantCustomDomain || undefined;
    
    /* ***** BEGIN NEW CSRF LOGIC ***** */
    
    req.session.csrfSecret = createCsrfSecret();
    await req.session.save();
    updateCsrfTokenAndCookie(req, res);
    
    /* ***** END NEW CSRF LOGIC ***** */

    return res.redirect(callbackData.returnUrl || '<replace_with_a_default_return_url>');
  } catch (err) {
    console.error(err);
    next(err);
  }
});



Update Logout Endpoint

Now, when a user logs out, we need to delete their CSRF cookie before redirecting to the Wristband Logout Endpoint.

// Logout endpoint
app.get('/auth/logout', async (req, res, next) => { 
  const { session } = req;
  const { refreshToken, tenantCustomDomain, tenantDomainName } = session;
  const logoutConfig = { refreshToken, tenantCustomDomain, tenantDomainName };
  res.clearCookie('session');
  
  /* ***** BEGIN NEW SESSION LOGIC ***** */
  
  res.clearCookie('CSRF-TOKEN');
  
  /* ***** END NEW SESSION LOGIC ***** */
  
  session.destroy();

  try {
    return await wristbandAuth.logout(req, res, logoutConfig);
  } catch (err) {
    console.error(err);
    return next(err);
  }
});

What’s Next

Lastly, let's enhance the frontend to be able to pass a CSRF request header when making API calls to your backend.