pythonjwtjwkauthlib

Python AuthLib Resource Server using a BearerTokenValidator with Multiple Strategies


I have a resource server (built with Flask, but not sure if that matters right now) that has a RESTful API. The API is secured with OAuth2 access tokens and scopes.

Currently the access tokens are opaque (not JWT) and the resource server needs to call the /oauth/token/info endpoint on the auth server to check if the access token is valid and get the list of scopes associated with the access token, and then validate the scopes granted against the ones required. We have some custom code for this.

We now want to start to use JWT access tokens so that we can avoid this call to the auth server, but we can't roll them out to all OAuth clients just yet, only some. So the resource server will be getting a mix of opaque access tokens and JWT access tokens. The JWT will be signed with a RS256 private/public key, and the public key will be available from the auth server at a /oauth/discovery/keys endpoint that the resource servers could hit on startup once and cache so that it doesn't need to hit it on every request, unless the public key changes and doesn't match the kid in the JWT.

While doing this, I was hoping we could get rid of some of the custom code we've written and use some tried and tested library for us, hence AuthLib.

However, I can't seem to find any good examples of how to configure a resource server to handle either of these cases individually, let alone both at the same time. The examples I see seem to assume the resource server has access to the access token database.

I'm assuming I will need to write my own BearerTokenValidator that handles this, but I was hoping there would be examples somewhere on how to go about that. Ideally with the ability to cache the public key for the JWT and only refresh when the JWT kid claim changes.

I was sort of hoping that a TokenInfoBearerTokenValidator and a JWTBearerTokenValidator existed that I could use that did most of the work for me. Maybe there are and I'm just missing it?


Solution

  • AuthLib 1.0 has been released with additional support fro JWTBearerTokens that makes this easier to accomplish now.