dorinclisu / fastapi-auth0

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

Is there any way to extend the class Auth0User in order to pass additional fields to the payload? (e.g. custom field) #40

Closed luciano-buono closed 8 months ago

luciano-buono commented 8 months ago
class Auth0User(Auth0UserBase):
    roles: list[str] = Field(None, alias=f'{settings.auth0_rule_namespace}/roles')  # type: ignore [literal-required]

I would like to extend your class Auth0 with an additional roles field, which I have added to my JWT The main goal is to be able to obtain this field from the JWT passed through the request

@app.get("/api/get_auth0_user")
def get_secure(user: Auth0User = Security(auth.get_user)):
    return {"message": f"{user}"}
## Here it would display id, permissions, email, and roles
dorinclisu commented 8 months ago

Besides the fact that reading roles in the backend is an anti-pattern (except if used only for literal display purpose), instead of relying only on granular permissions, yes it's possible to extend, you're already done the python / fastapi part.

However, in order for that to work, you need to use auth0 actions to add the roles as custom claim to the jwt. A few lines of javascript code will be required in your auth0 console.

luciano-buono commented 8 months ago

Hi, yes I have already done that Action Flow in the login for Auth0

I needed to extend not only Auth0User, also Auth0 class in my own file