jpadilla / pyjwt

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

Minimal example of implementation with encode and decode #951

Closed brunolnetto closed 1 month ago

brunolnetto commented 3 months ago

I implemented a minimal example for this library on my FastAPI app. However, I do not know how to add the JWT_SECRET to the JWT instance using library objects.

Expected Result

from datetime import timedelta
from os import environ
from typing import Dict
from time import time
from jwt import JWT

JWT_SECRET = str(environ.get('JWT_SECRET'))
JWT_ALGORITHM = str(environ.get('JWT_ALGORITHM')) 

def token_response(token: str):
    return {
        "access_token": token,
        "token_type": "bearer"
    }

def signJWT(user_id: str, expires_delta: timedelta) -> Dict[str, str]:
    payload = {
        "user_id": user_id,
        "expires": time() + 600
    }
    jwt_obj = JWT()

    token = jwt_obj.encode(payload, key=JWT_SECRET, alg=JWT_ALGORITHM)

    return token_response(token)

def decodeJWT(token: str) -> dict:
    try:
        jwt_obj = JWT()

        decoded_token = jwt_obj.decode(token, key=JWT_SECRET, alg=JWT_ALGORITHM)

        return decoded_token if decoded_token["expires"] >= time.time() else None
    except:
        return {}

Actual Result

E TypeError: key must be an instance of a class implements jwt.AbstractJWKBase

Reproduction Steps

Code provided above

System Information

$ python -m jwt.help
/home/brunolnetto/.rye/py/cpython@3.12.1/install/bin/python3: Error while finding module specification for 'jwt.help' (ModuleNotFoundError: No module named 'jwt')

This command is only available on PyJWT v1.6.3 and greater. Otherwise, please provide some basic information about your system.

Ubuntu 20.04 PyJWT==1.7.1

github-actions[bot] commented 1 month ago

This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 7 days