How should I store access token from a 3rd part api

1.6k Views Asked by At

Hi i am using meteorjs and a 3rd party api to create users on 3rd party's database.

I am getting access tokens with oauth2 and tokens have 2 hour expiry. After getting the access token with an async function I use it with couple of different methods.

However instead of calling an async function every time I need an access token, I would like to store it on server until it expires.

what is the best practice to store them securely and use it globally on the server?

many thanks in advance

2

There are 2 best solutions below

0
On BEST ANSWER

I end up using global var to store the token on server;

token = '';

Meteor.methods({
  refreshToken: function () {
    token = getToken();
  ...
});

and now

token

is available for all methods. and I also check if the token still valid and refresh the token if the expiry is within 300 seconds.And the code for that part is as follows:

    const EXPIRATION_WINDOW_IN_SECONDS = 300;
    const expirationTimeInSeconds = token.expires_at.getTime() / 1000;
    const expirationWindowStart = expirationTimeInSeconds - EXPIRATION_WINDOW_IN_SECONDS;
    const nowInSeconds = (new Date()).getTime() / 1000;
    const shouldRefresh = nowInSeconds >= expirationWindowStart;
       if (shouldRefresh) {
           try {
               //refresh the token
           } catch (error) {
               console.log('Error refreshing access token: ', error.message);
           }
       }
1
On

RFC6819 - Threat Model and Security Considerations define several threat vectors and counter measurements. In that section 5.3.3. Store Secrets in Secure Storage define best practices on how to store secrets.

Most multi-user operating systems segregate the personal storage of different system users. Moreover, most modern smartphone operating systems even support the storage of application-specific data in separate areas of file systems and protect the data from access by other applications

Given that you are running a JavaScript based front end application, best approach is to store access token in HTML5 web storage.

It allows you to access token whenever required for your API calls. Also, if browser implementation is secure (ex:- Contains all security patches etc.) this will provide a secure storage denying access to other applications. There also, you have the option to use sessionStorage to provide added security of removing access token on tab close.