dorinclisu / fastapi-auth0

FastAPI authentication and authorization using auth0.com
MIT License
230 stars 39 forks source link

Secure only if using `auth.get_user` as a function parameter #4

Closed amitrahav closed 3 years ago

amitrahav commented 3 years ago

When securing endpoint only by decorator dependencies, it doesn't secure it at all...

Here is the relevant code rip:

 @app.get("/templates", response_model=Response[List[Template]], dependencies=[Depends(auth.implicit_scheme)])
def list_templates():
    data = get_static("templates.json")
    return Response(data=data)

I'm expecting to get 403 when I don't send any Authorization header, but i get 200: curl --location --request GET 'http://localhost:8000/templates'

Only when I use auth.get_user as a parameter for list_templates function like this:

@app.get("/templates", response_model=Response[List[Template]], dependencies=[Depends(auth.implicit_scheme)])
def list_templates(user: Auth0User = Security(auth.get_user, scopes=['read:users'])):
    data = get_static("templates.json")
    return Response(data=data)

I get 403 when not sending Authorization header.

So, am I missing something? or do I have to use user for authentication will invoke?

dorinclisu commented 3 years ago

This is expected behavior, the auth schemes only have documentation purposes (and allow swagger UI to obtain the token) and do not involve any verification on fastapi side. This happens exclusively in auth.get_user.

In your case, you can do this to secure the endpoint:

@app.get("/templates",
    response_model=Response[List[Template]],
    dependencies=[Depends(auth.implicit_scheme), Depends(auth.get_user)])
def list_templates():
   data = get_static("templates.json")
   return Response(data=data)

See the tests for detailed usage of auth (lines 38-69) https://github.com/dorinclisu/fastapi-auth0/blob/master/tests/test_auth.py