0

I have an application, in which I have to fetch a list of users. The API to fetch the list requires an authentication token, which expires every 1 hour. So, in order to fetch the users, I first need to make a token call and post that I need to make the fetch call. How can I cache the token which is valid for 1 hour in Node? We have multiple pods, so I need a distributed cache to make sure that the token value is the same across the pods. Will it be possible to implement it in node and how to implement it? Any kind of resources/tutorials would be really helpful.

Frosted Cupcake
  • 1,909
  • 2
  • 20
  • 42
  • What are you trying to do? Is Node.js the client that needs credentials to access some other service, after obtaining a token? Why would all processes need to have the same token - can't they all have their own separate tokens that are all valid at the same time? – Robert Kawecki Mar 25 '21 at 10:05
  • @RobertKawecki Actually we are hitting some third-party service that provides a token that could be used to access their APIs. The token expires every 1 hour. So, to save token call and post that API calls every time, I was thinking of storing the token in the node which would save token call from every client. – Frosted Cupcake Mar 25 '21 at 10:08

1 Answers1

0

So you're calling an external service, but you need a valid token that you have to obtain first.

Take a look at how existing software tackles it. For example, Microsoft's Graph API SDK (which also uses bearer token auth): https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md

You inject an "authentication provider" that authenticates and retrieves a token from the remote service when necessary. Next, when you need to make a call to the API, the client checks if it has a token in-memory. If it doesn't (or if it's expired), it asks the authentication provider for a new token. So, the in-memory cache layer is in the client object.

Another approach is in-memory caching, but in the Authentication Provider layer - then, the client can blindly ask it for a token every time, and let the Provider decide whether to use the current token or ask for a new one.

I would refrain from putting the token on a network-accessible cache - it opens up a potential security hole for leaking the token, and does not seem to serve any purpose.

Robert Kawecki
  • 2,218
  • 1
  • 9
  • 17