When developing microservices which call each other using OAuth2/client credentials auth, where services have their own credentials, I regularly find myself writing code to:
- Exchange a static
client_id
andclient_secret
for a time-limited JWT Bearer token. - Use that token many times, for many requests, until it expires (or is close to expiring).
- Get a fresh token, and repeat.
Given that caching is one of the two hard problems in computer science (along with naming and off-by-one errors), I'd love to be able to find a library that already does this, or failing that, write one.
A wish list of features:
- Underlying non-blocking http client.
- The user can configure details about authentication once, and then not have to think about it every time they make an api request.
- The user can use it to call any arbitrary api.
- After writing code to define the api endpoints/models/etc, there is some simple method like
.invokeWithAuth
or something that can handle requesting a token (if necessary) or adding a valid token (if cached) to the request. - Except perhaps when request volume is very low, most requests should use a cached token, rather than requesting a new one with each request.
- The library should have an effective means of managing token expiration, like handling a 401 response with a retry using a new token, or preemptively refreshing tokens before they expire.
- The library should be able to determine (perhaps by a user-implemented interface) how long a particular token is valid for, from the token response.
I would be happy to find a library that does even some of that, but I've had no success. Does anyone know of or use a library that does a good job solving this problem? Are there other solutions I overlooked? I could write code to do all of this, but I would probably miss some edge cases.
I'm actually writing code in scala, so a scala library would be even better than a java one, but java libraries are perfectly usable from scala.