jpadilla / pyjwt

JSON Web Token implementation in Python
https://pyjwt.readthedocs.io
MIT License
5.1k stars 682 forks source link

PyJWT async #956

Open padrepitufo opened 4 months ago

padrepitufo commented 4 months ago

I am somewhat new to contributing to a python library, and I am not sure if the code I'm supplying is needed/wanted-by/appropriate-for this project. If there is already a suggested way to use PyJWT within an asynchronous context (like FastAPI) I would like guidance. If something like this could be useful I can add tests or make changes to align the code with the style of the project.

The purpose of this PR is to mitigate blocking code/calls such as represented in this tutorial (to get_signing_key_from_jwt):

class VerifyToken:
    """Does all the token verification using PyJWT"""
    # ...
    async def verify(self,
                     security_scopes: SecurityScopes,
                     token: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer())
                     ):
        # ...
        try:
            signing_key = self.jwks_client.get_signing_key_from_jwt( # 👈 current behavior
                token.credentials
            ).key
        except jwt.exceptions.PyJWKClientError as error:
            # ...
        return payload
    # ...

I wish to call it like so

class VerifyToken:
    """Does all the token verification using PyJWT"""
    # ...
    async def verify(self,
                     security_scopes: SecurityScopes,
                     token: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer())
                     ):
        # ...
        try:
            signing_key = await self.jwks_client.get_signing_key_from_jwt_async( # 👈 desired behavior
                token.credentials
            ).key
        except jwt.exceptions.PyJWKClientError as error:
            # ...
        return payload
    # ...

Thank you in advance for any guidance/direction you provide.

padrepitufo commented 4 months ago

apologies on the pre-commit failure, it wasn't working on my end for some reason so I pushed with 🤞 . I'll fix that. And of course, there is no test coverage - but I didn't want to make a deeper investment until I got some feedback.

padrepitufo commented 4 months ago

fixed (but still a lot of tests pending your response @jpadilla )

yossivainshtein commented 4 months ago

I'm not active on the project, I'm only here to say that YES, i'd love to have this change, This method (get_signing_key_from_jwt) is blocking and should be async.

I was looking for this functionality today and found this PR, would love to see this included.

Omar12e44 commented 4 months ago

xD

Dazix commented 1 month ago

Any update on this? @jpadilla