Geert-Jan
Geert-Jan

Reputation: 18915

should OAuth2Client be created per request or cached per user?

I'm using the node version of the google api client. i.e.: google-api-nodejs-client.

As part of this I'm setting up oauth-flow (the 'google webserver' flow to be exact.)

As part of authentication this consists of doing calls like:

 var oauth2Client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

and

 oauth2Client.setCredentials(userSpecificTokens)

Obviously, the first call is app-specific, whereas the second call is user-specific.

What is considered good practice in this case? either:

  1. have 1 oauth2Client and cache/save tokens per user and inject them using oauth2Client.setCredentials(userSpecificTokens) on each and every request. This essentially creates a new oauth2Client per request.
  2. have a oauthClient per user including oauth2Client.setCredentials(userSpecificTokens) already applied which is created when needed and cached afterwards.

Upvotes: 11

Views: 1505

Answers (1)

Justin Maat
Justin Maat

Reputation: 1975

I believe your first approach is the correct one

have 1 oauth2Client and cache/save tokens per user and inject them using oauth2Client.setCredentials(userSpecificTokens) on each and every request.

However, this line isn't correct

This essentially creates a new oauth2Client per request.

The oauth2client is created only once, when you've newed it - new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

setCredentials() just swaps the credentials that are stored in that OAuth2Client object. Basically, what this means is that if you went for your 2nd approach, you'd have many additional instantiated OAuth2Client's unnecessarily. The only time you would ever need to instantiate a "new" Oauth2Client is when you want to connect with a different token/key.

It's somewhat common to store the tokens on a database or session and have them reused exactly as you've described by setting the credentials on the single instance of your client. (https://security.stackexchange.com/questions/72475/should-we-store-accesstoken-in-our-database-for-oauth2)

For reference, the docs give some insight and basically describe your first approach - https://github.com/google/google-api-nodejs-client/#request-level-options

You can specify an auth object to be used per request. Each request also inherits the options specified at the service level and global level.

Upvotes: 2

Related Questions