Search code examples
node.jsoauth-2.0google-apigoogle-oauthgmail-api

How to handle new refresh token events for multiple users in google api


I'm working on an MVP for a web app using nodejs. I use gmail/google API for authentication and login. I've set up the login and OAuth2.0 and it's working. However, there is one part in the documentation I'm not sure about. Here is the documentation I'm referring to

https://github.com/googleapis/google-api-nodejs-client

Specifically the "Handle Refresh Tokens" part.

It says that I should listen to the tokens event for new refresh_tokens and store the new refresh_token in the database

oauth2Client.on('tokens', (tokens) => {
  if (tokens.refresh_token) {
    // store the refresh_token in my database!
    console.log(tokens.refresh_token);
  }
  console.log(tokens.access_token);
});

What I don't understand is how would you know which refresh_token is for which user? Would you have to associate a unique identifier earlier in the process, then when the event occurs check for the identifier?


Solution

  • Yes, you need to create a unique identifier and map that to the refresh token as the value if you're going to store it in a database, which is recommended.

    Remember that the refresh token grants another access token without requiring the user to authenticate. Which means if you use the refresh token with a request for another user, you're giving the other user access!

    A common way to create a unique identifier is with a session token or session id as the unique identifier. You can use that as the key mapped to the refresh token in your database. See here for some explanation and things to watch out for: OWASP Session Management Cheat Sheet

    You also need to think about how you're going to store that unique identifier. So you know when to use the associated refresh token at the right time. It depends on your use case, but if you're using it to avoid requiring the user to re-authenticate, stored securely in a cookie is often how it's done. So, the next time the user revisits your app, you can check for the cookie and lookup the unique identifier in your database.

    From the same cheat sheet.

    And MDN has some helpful docs on cookies.

    OWASP Nodejs cookie security

    If you're doing something like running some kind of automation for the user when they aren't present, it'll look different. Encrypting the user's email or whatever identifier you're using for the use is one way. Use the result of that as the key/session token. That's, of course, a simplified view, but it gives you an idea.