2

I am trying to add a custom decorator to secure fastapi endpoints to list of users. The incoming payload has JWT data in the header and/or cookies.

With out the decorator, fastapi_jwt_auth allows/denies to the endpoints as long as the token is valid. However when adding the custom decorator, it fails to pass the header/cookie payload to the decorator to be parsed and return the correct response if valid/invalid.

From what I could understand from this post it should be able to obtain the payload from the router function. However it only seems to create a blank class object.

from functools import wraps

from fastapi import Depends
from fastapi.responses import JSONResponse

from fastapi_jwt_auth import AuthJWT

def auth(users: Union[List[str], None, str] = None):
    def decorator_auth(func):
        @wraps(func)
        def wrapper_auth(*args, **kwargs):
            Authorize.jwt_required()
            jwt_username = Authorize.get_raw_jwt()['username']
            if jwt_username not in users:
                return JSONResponse(
                    status_code=401,
                    content={"detail": "Unauthorized"} ) 
            return func(*args, **kwargs)
        return wrapper_auth
    return decorator_auth

@app.get('/data')
def secure_data(Authorize: AuthJWT = Depends()):
    Authorize.jwt_required()
    return JSONResponse(
            status_code=200,
            content={"detail": "Payload only all with valid tokens."})

@app.get('/data1')
@auth(users=['user1', 'user3')
def secure_data_1(Authorize: AuthJWT = Depends()):
    return JSONResponse(
            status_code=200,
            content={"detail": "Payload only for User 1 and User 3."})

@app.get('/data2')
@auth(users=['user2'])
def secure_data2(Authorize: AuthJWT = Depends()):
    return JSONResponse(
            status_code=200,
            content={"detail": "Payload only for User 2."} )

0 Answers0