Navigation

You may want to store additional information in the access token which you could
later access in the protected views. This can be done with the
user_claims_loader() decorator, and the data can be
accessed later in a protected endpoint with the
get_jwt_claims() function.

Storing data in an access token can be good for performance. If you store data
in the token, you wont need to look it up from disk next time you need it in
a protected endpoint. However, you should take care what data you put in the
token. Any data in the access token can be trivially viewed by anyone who can
read the token. Do not store sensitive information in access tokens!

fromflaskimportFlask,jsonify,requestfromflask_jwt_extendedimport(JWTManager,jwt_required,create_access_token,get_jwt_claims)app=Flask(__name__)app.config['JWT_SECRET_KEY']='super-secret'# Change this!jwt=JWTManager(app)# Using the user_claims_loader, we can specify a method that will be# called when creating access tokens, and add these claims to the said# token. This method is passed the identity of who the token is being# created for, and must return data that is json serializable@jwt.user_claims_loaderdefadd_claims_to_access_token(identity):return{'hello':identity,'foo':['bar','baz']}@app.route('/login',methods=['POST'])deflogin():username=request.json.get('username',None)password=request.json.get('password',None)ifusername!='test'orpassword!='test':returnjsonify({"msg":"Bad username or password"}),401ret={'access_token':create_access_token(username)}returnjsonify(ret),200# In a protected view, get the claims you added to the jwt with the# get_jwt_claims() method@app.route('/protected',methods=['GET'])@jwt_requireddefprotected():claims=get_jwt_claims()returnjsonify({'hello_is':claims['hello'],'foo_is':claims['foo']}),200if__name__=='__main__':app.run()