tiangolo / fastapi

FastAPI framework, high performance, easy to learn, fast to code, ready for production
https://fastapi.tiangolo.com/
MIT License
73.34k stars 6.18k forks source link

hi @chrisK824, my use case is that I have a router which has a global dependency to validate jwt tokens. then, i also have endpoints which come under the secure router where i want to check for the permissions, so for example #11554

Closed rohantandon25 closed 2 months ago

rohantandon25 commented 2 months ago

hi @WilliamStam, my use case is that I have a router which has a global dependency to validate jwt tokens. then, i also have endpoints which come under the secure router where i want to check for the permissions, so for example

secure_router = APIRouter(dependencies=[Security(auth0_token)])
@secure_router.get("/api/{org}/user",
                    dependencies=[Depends(PermissionsValidator(["read:{org}"]))])

and PermissionsValidator is defined as:

class PermissionsValidator:
    def __init__(self, required_permissions: list[str]):
        self.required_permissions = required_permissions

    def __call__(self, token: JWTPayload = Security(auth0_token)):
        token_permissions = token.permissions
        token_permissions_set = set(token_permissions)
        required_permissions_set = set(self.required_permissions)

        if not required_permissions_set.issubset(token_permissions_set):
            raise PermissionDeniedException

it seems to me that the jwt token will be validated twice in this scenario - is it possible to do it only once?

Originally posted by @rohantandon25 in https://github.com/tiangolo/fastapi/discussions/10388#discussioncomment-9359260