Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache OAuth2 tokens in SpringBoot application?

I am implementing a Spring Boot application, in which the methods are calling third party REST endpoints. This REST API is accessible after OAuth2 authentication. That is why I retrieve tokens from the third party (various users can use my application and respectfully call the REST endpoints) and use these tokens for authorization in order to call the endpoints. But in the current implementation this happens before every call. That is why I would like to ask for advice how to cache these tokens and whether this is a good practice at all? Also the tokens expire in 1 hour.

like image 647
Ivajlo Iliev Avatar asked Sep 26 '19 15:09

Ivajlo Iliev


1 Answers

You should not cache access tokens on the backend of a web application ,if you can store them client side and send them with each request.

In case you don't have possibility to store it at client side (possible case your API is talking to some message client like USSD,SMS etc),It will be expensive to get an OAuth access token, because it requires an HTTP request to the token endpoint. This case is a good example where you can cache tokens whenever possible. You can make use of REDIS if you have multiple instances.

REMEMBER : Tokens are sensitive data, because they grant access to a user's resources. (Moreover, unlike a user's password, you can't just store a hash of the token.) Therefore, it's critical to protect tokens from being compromised. You can make use of encryption.Do check below links for more details :

https://auth0.com/docs/best-practices/token-best-practices.

https://github.com/auth0/express-openid-connect/blob/master/EXAMPLES.md#5-obtaining-and-storing-access-tokens-to-call-external-apis

https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/token-cache

As per Auth0 Token Best Practices

Store and reuse. Reduce unnecessary roundtrips that extend your application's attack surface, and optimize plan token limits (where applicable) by storing access tokens obtained from the authorization server. Rather than requesting a new token, use the stored token during future calls until it expires. How you store tokens will depend on the characteristics of your application: typical solutions include databases (for apps that need to perform API calls regardless of the presence of a session) and HTTP sessions (for apps that have an activity window limited to an interactive session). For an example of server-side storage and token reuse, see Obtaining and Storing Access Tokens to Call External APIs in our Github repo

like image 127
Googi Avatar answered Nov 10 '22 16:11

Googi