Search code examples
expresscookiesaxiosjwtrefresh-token

Proper way to do jwt refresh tokens with express


I'm thinking of a proper pattern for implementing refresh tokens, but on few steps, I have some questions. I am using nextjs with axios on the frontend and express with cookie-session on the backend. Here are steps I'm thinking of:

  1. Client sends a log-in request. After logging in I put the access token in the session object and the refresh token into res.cookie, both secure and httpOnly.
  // for simplicity options are left out
  req.session = { accessToken };
  res.cookie("refreshToken", refreshToken)
  1. On every request with axios I supply just the access token. Here's where the first question arises. How would I supply only the access token, without sending the refresh token too, if both are httpOnly?
  2. If the access token is valid do whatever is needed. If not, need to get the refresh token and compare it to a stored one, and so on. Here's the second question. While I understand I need to retrieve the refresh token in this step, how would I do it properly?

Any more advice would be great, thanks.

[EDIT] After some thought I realised that making access token not httpOnly would allow me to send just access token, which would solve my problem. But if that is incorrect please let me know.


Solution

  • Here is the standard pattern - as in this code of mine:

    • Client sends access token (which may be in an HTTP Only cookie)
    • When it expires they try to refresh the access token by calling a /refresh endpoint
    • If the refresh succeeds they retry the API request with the new access token
    • Otherwise the client redirects the user to sign in again

    Don't make the access token non HTTP Only, since any malicious code could then grab it from document.cookie.

    This also allows you to set a path of /refresh for the RT cookie, so that it is only sent on refresh requests.

    Also ensure that cookies containing tokens are strongly encrypted (AES256) using a symmetric key only known server side. This Express library will do the work for you.