Reputation: 21
I'm trying to implement role based access control in my code. I created a roles table and added a few roles to it.
Using a couple of YouTube tutorials and the docs, I got the following code:
decorators.py:
from functools import wraps
from flask import make_response
from flask_jwt_extended import get_current_user
def auth_role(role):
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
current_user = get_current_user()
roles = role if isinstance(role, list) else [role]
if all(not current_user.has_role(r) for r in roles):
return make_response({"msg": f"Missing any of the following roles {':'.join(roles)}"}, 403)
return fn(*args, **kwargs)
return decorator
return wrapper
routes.py:
@app.route('/test')
@auth_role("admin")
@jwt_required
def test():
return "Hello"
init.py:
app = Flask(__name__)
app.config.from_object(Config)
jwt = JWTManager(app)
Everything has been imported correctly.
However, whenever I try to go to 'localhost:5000/test', I get the following error:
RuntimeError: You must call @jwt_required()
or verify_jwt_in_request()
before using this method
Does anyone know how to solve this problem?
Upvotes: 2
Views: 115
Reputation: 11
this is due to your decorators order
@jwt_required
@app.route('/test')
def test():
return "Hello"
will return in the same Runtime error
you have to call get_current_user() after token is extracted and decoded by jwt_extended lib. a working example here Implementing roles with Flask-JWT-Extended
Upvotes: 1