Implementing roles with Flask-JWT-Extended

Viewed 658

I am currently developing an flask api that uses flask-jwt-extended to protect endpoints. I have the jwt required decorator working correctly but I would like to add roles to have more granular control over access. In my imagination it would be best to have three tables Users, Roles and UserRoles. UserRoles would map users to roles using foreign ids and then use a custom decorator to check for each endpoint.

I have never done this before, how would you implement this and why?

2 Answers

As you suggested, having some basic tables and methods + decorators is the way to go.

You can also look into how this is implemented in Flask-Security (or in packages Flask-Login and Flask-Principal, which are used in Flask-Security). It can give you some suggestions on what kind of functions you'd like to have.

According to the docs, it should be possible with custom decorators, like this:

from flask_jwt_extended import get_jwt
from flask_jwt_extended import verify_jwt_in_request


# Here is a custom decorator that verifies the JWT is present in the request,
# as well as insuring that the JWT has a claim indicating that this user is
# an administrator
def admin_required():
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            verify_jwt_in_request()
            claims = get_jwt()
            if claims["is_administrator"]:
                return fn(*args, **kwargs)
            else:
                return jsonify(msg="Admins only!"), 403

        return decorator

    return wrapper

Just make sure that you save roles information using additional claims.

Related