DEV Community

Cover image for Caching OAuth2 Token using Redis
Sibelius Seraphini for Woovi

Posted on

Caching OAuth2 Token using Redis

When consuming external services, it is common to use OAuth2 token as the authorization pattern.

OAuth2 stands for "Open Authorization", and the result returned by the https://example.com/oauth2/token is usually like this one:

{
   access_token: 'access_token',
   token_type: 'Bearer',
   expires_in: 3600,
}
Enter fullscreen mode Exit fullscreen mode

You want to reuse the access_token until it is valid, instead of always calling oauth2/token endpoint every time. This can reduce up to 1/2 seconds if the external service you are consuming is slow.

Caching OAuth2 Token using Redis

Redis is an in-memory key value database that can let you save some data with expiration time. It is the perfect option to cache data with an expiration time.

Let's see how to read and set some data with expiration using Redis using node and ioredis package

import Redis from 'ioredis'

const redis = new Redis();

// save value stringified in a given key for some seconds
redis.setex(key, seconds, JSON.stringify(value));

// read the value of the key, it will return null if the key is expired
redis.get(key); 
Enter fullscreen mode Exit fullscreen mode

Given the 2 commands above we can implement a higher order function to make our oauth2Token request cacheable with Redis

const withAccessTokenCache = (oauth2TokenRequest, cacheKey = 'oauth2token') => async () => {
  const cachedToken = await redis.get(cacheKey);
  if (cachedToken) {
    return JSON.parse(cachedToken);
  }

  const tokenResponse = await oauth2TokenRequest();

  if (tokenResponse.access_token && tokenResponse.expires_in) {
    await redis.setex(cacheKey, tokenResponse.expires_in, JSON.stringify(tokenResponse));
  }

  return tokenResponse;
}
Enter fullscreen mode Exit fullscreen mode

withAccessTokenCache will first try to read the tokenResponse from the Redis cache, and only request a new token if the current one was expired.

Here is the final example:

const providerOAuth2Token = async () => {
  const url = `https://example.com.br/oauth2/token`;

  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
  };

  const response = await fetch(url, options);
  return await response.json();
};

const providerOAuth2TokenWithCache = withAccessTokenCache(providerOAuth2Token);
Enter fullscreen mode Exit fullscreen mode

To sum up

Woovi provide instant payments solutions, so we need to make our services as fast as instant. We use cache to make slow external services to look fast.

What else are you caching?


Woovi
Woovi is a Startup that enables shoppers to pay as they like. To make this possible, Woovi provides instant payment solutions for merchants to accept orders.

If you want to work with us, we are hiring!


Photo by Wells Hall on Unsplash

Top comments (0)