Search code examples
node.jsreactjsoauth-2.0access-tokenrefresh-token

Storing Oauth access token and refresh tokens


I am currently integrating some third party api where they use oauth and my app is mern stack. I currently implemented oauth flow to only happen in the backend, Here is a sample of my code.

when user clicks a button to authenticate from the client, I handle the redirect from server

export const getAuthCode = async (req: Request, res: Response): Promise<void> => {
  res.redirect(OAUTH_URL)
}

when the third party api redirects I parse out the code and request access and refresh token

export const getAccessAndRefreshToken = async (req: Request, res: Response): Promise<void> => {
  const { code } = req.query

  try {
    // *options contain client, secret, redirect uri and code*
    const { data } = await axios.post(OAUTH_URL, options)

    console.log(data) // *contains access and refresh tokens*

    // save access and refresh token to httponly cookie
    // redirect user

  } catch (err) {
    console.log(err)
  }
}

question #1 - is this the right way to implement oauth flow?

question #2 - how do I store access and refresh token? currently I set access and refresh tokens in httpOnly cookie, I have no way to send user id to getAuthCode from client to save the refresh token into user table in databse, since it's just a button click.


Solution

    1. The OAuth flow looks pretty standard - aim to also use PKCE if your provider supports it.

    2. The simplest option is to use a library and store tokens in secure cookies, while also ensuring that you use strong options such as these:

    • HTTP Only
    • Secure
    • AES256 Encrypted - with a symmetric key only known by your back end
    • SameSite=strict

    This mitigates browser risks, keeps your application code simple and prevents the overhead and risks involved in managing your own token store - it is best to leave this type of storage to specialist OAuth systems.

    OAuth tokens can be a few KB though, so it is possible that multiple cookies could be needed to avoid exceeding browser limits.