Should OAuth2Client be created for each request or cached for each user?

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

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

As part of authentication, making calls such as:

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

and

  oauth2Client.setCredentials(userSpecificTokens) 

Obviously, the first call is application specific, while the second call is user specific.

What is considered good practice in this case? or:

  • have 1 oauth2Client and cache / save tokens per user and enter them using oauth2Client.setCredentials(userSpecificTokens) for each request. This essentially creates a new oauth2Client for each request.
  • has oauthClient for each user, including oauth2Client.setCredentials(userSpecificTokens) , already applied, which is created when necessary and then cached afterwards.
+5
source share
1 answer

I believe that your first approach is correct.

have 1 oauth2Client token and cache / save for each user and enter them using oauth2Client.setCredentials (userSpecificTokens) for each request.

However, this line is incorrect

This essentially creates a new oauth2Client for each request.

oauth2client is created only once when you enter it - new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);

setCredentials() simply swaps the credentials that are stored in this OAuth2Client object. Basically, this means that if you went for your second approach, you would have many additional instances of OAuth2Client unnecessarily. The only time you need to create a new "Oauth2Client" is when you want to connect to another token / key.

It is well known that storing tokens in a database or session and reusing them is the same as you described by setting the credentials in one 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 that will be used for each request. Each request also inherits the parameters specified at the service level and at the global level.

+1
source

Source: https://habr.com/ru/post/1200678/


All Articles