Skip to content
Advertisement

Secured endpoints in FastApi using enum

In my app, I want to apply access to a given endpoint based on a role, which is an enum. The way it all works is that a logged in (authorized) user, wants to get access to some resources, or create a new user etc…, then his jwt token is decoded, so we can see his roles (enum). I’m going to create 3 functions (permission_user, permission_admin, permission_manager) that read the roles of the user and based on it, give access or not. I know that I could create 6 functions (permutations), such as permission_user_and_manager, but I want to solve this in a more professional way. I would like to do something based on:

JavaScript

Unfortunately it doesn’t work, do you know any solutions?

Advertisement

Answer

I would supply the value as another dependency which will return a 403 if the enum is not an appropriate value. I would expect a separate dependency that handles the actual auth and returns an enum value for the permissions (e.g. something like AuthRole).

JavaScript

In your definition of the endpoint route, you can specify this method as a depends that must be performed before the call happens. You could also apply this to an ApiRouter class to avoid duplication.

JavaScript

Now you will only enter the body of fetch_users if the admin_permissions dependency does not raise the 403 response code.

If you want to parameterize this further, you can use an advanced dependency that uses a class instances __call__ method to perform the work. Then you can provide multiple roles that are acceptable instead of just one. That would look something like this:

JavaScript

Full example to play with:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement