authlib icon indicating copy to clipboard operation
authlib copied to clipboard

Allow reading an unvalidated JWT's header

Open thatguysimon opened this issue 4 years ago • 6 comments

Is your feature request related to a problem? Please describe.

When validating a JWT using a JWKS, it is common to read the kid claim from the JWT's header in order to pull the correct JWK from the set. For example: https://auth0.com/docs/quickstart/backend/python/01-authorization#create-the-jwt-validation-decorator

Currently in order to read the contents of the JWT we have to initialize and run a JWTBearerTokenValidator instance, but we can't initialize it without the key that we want to get from the JWKS. So we're sort of stuck in a deadlock here.

Describe the solution you'd like

A helper function, similar to PyJWT's get_unverified_header, which allows reading an unvalidated JWT's header.

Describe alternatives you've considered

Using PyJWT itself, but it's a shame to add another dependency just for this.

This library is awesome by the way, thanks!!

thatguysimon avatar Dec 23 '20 13:12 thatguysimon

@thatguysimon our key accepts a function:

def load_key(header, payload):
    kid = header['kid']
    return keys[kid]

jwt.decode(s, key=load_key, ...)

jwt.decode also support jwks as key:

jwks = {'keys': [...]}

jwt.decode(s, key=jwks, ...)

However, I would like to add such a method in the future.

lepture avatar Dec 25 '20 03:12 lepture

Thanks @lepture, this was very helpful! Is it documented anywhere? I couldn't find anything about this in the docs.

thatguysimon avatar Jan 10 '21 12:01 thatguysimon

In my use case, getting the key requires making a call with the kid using async API bindings. I don't want to have to start up another loop in another thread so being able to get an unverified header would be very useful.

relsunkaev avatar Mar 28 '22 21:03 relsunkaev

I'm in the same deadlock situation - I need to read the unvalidated header at the moment when the key for decoding is not yet available. It would be great if authlib would have this feature. For now, I had to solve it by using a different library, unfortunately.

evelyn9191 avatar Jan 11 '24 11:01 evelyn9191