Reputation: 445
I have a project i have to use flask_restful for multiple users using flask_jwt_extended. How do i implement it for 3 types of authentication ? i have one members(users) , one for creator and the last one for admin. how do i do so? i have created models.py, resource. py can anyone guide me accordingly
i tried a lot of videos, but none of them were helpful reguarding the same but most of them want to use blue prints in flask also most of them don't use multiple login criteria i have to use this at backend with vue.js 3 at front end i am lot confused
Upvotes: 1
Views: 97
Reputation: 1627
When creating the jwt claims, you can add a "permissions" parameter. When flask checks the JWT, you can prevent access to this route if the jwt does not contain this specific permission.
something like this decorator:
def permissions_required(route_permissions="admin")
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
user_permissions = claims.get("permissions")
if user_permissions == route_permissions:
return fn(*args, **kwargs)
else:
raise NoAuthorizationError
return decorator
return wrapper
it may look a bit confusing, but all it does is execute the route only if the claims in the jwt match the role defined by the route. otherwise, it aborts with a NoAuthorizationError. (or a custom 403 if you really want to)
this would prevent access to this route for any users that do not have the "admin" permissions.
you'd use it like this in a route:
class AdminRoute(Resource):
@staticmethod
@permissions_required(route_permissions="admin")
def get():
# protected route, requires admin permissions
you can find a similar example in the read-the-docs pdf here:
https://flask-jwt-extended.readthedocs.io/_/downloads/en/stable/pdf/
on chapter 11, page 43, which simply uses "admin_required" as the decorator
To add the claims to the JWT payload, you need this code when generating a JWT:
from flask_jwt_extended import JWTManager
jwt = JWTManager(None)
jwt.additional_claims_loader(additional_claims_callback)
def additional_claims_callback(identity):
# if this user is an admin, add the admin permissions
claims.update({"permissions": "admin"})
# if the user is a creator, add the "creator" permissions
claims.update({"permissions": "creator"})
# etc...
return claims
Upvotes: 1
Reputation: 31
You can implement decorators for this. Create a new file named middleware.py and define a decorator function named let's say @permission_required(role="Creator/Member/Admin"). Under the decorator you can define your logic that for which user you want to give what permission. If you are storing the roles and permissions in a different table you can also query from that table as well.
Upvotes: 1
Reputation: 26
Upvotes: 1