Navigation

You can create your own decorators that extend the functionality of the
decorators provided by this extension. For example, you may want to create
your own decorator that verifies a JWT is present as well as verifying that
this token has sufficient permissions/roles to access an endpoint.

Verify Tokens in Request is a list of functions that can be
used to build your own decorators (these are also what all the default
decorators provided by this extension use internally).

Here is an example of how this might look.

fromfunctoolsimportwrapsfromflaskimportFlask,jsonify,requestfromflask_jwt_extendedimport(JWTManager,verify_jwt_in_request,create_access_token,get_jwt_claims)app=Flask(__name__)app.config['JWT_SECRET_KEY']='super-secret'# Change this!jwt=JWTManager(app)# Here is a custom decorator that verifies the JWT is present in# the request, as well as insuring that this user has a role of# `admin` in the access tokendefadmin_required(fn):@wraps(fn)defwrapper(*args,**kwargs):verify_jwt_in_request()claims=get_jwt_claims()ifclaims['roles']!='admin':returnjsonify(msg='Admins only!'),403else:returnfn(*args,**kwargs)returnwrapper@jwt.user_claims_loaderdefadd_claims_to_access_token(identity):ifidentity=='admin':return{'roles':'admin'}else:return{'roles':'pesant'}@app.route('/login',methods=['POST'])deflogin():username=request.json.get('username',None)access_token=create_access_token(username)returnjsonify(access_token=access_token)@app.route('/protected',methods=['GET'])@admin_requireddefprotected():returnjsonify(secret_message="go banana!")if__name__=='__main__':app.run()