Navigation

We provide what we think are sensible behaviors when attempting to access a
protected endpoint. If the access token is not valid for any reason (missing,
expired, tampered with, etc) we will return json in the format of {‘msg’: ‘why
accessing endpoint failed’} along with an appropriate http status code
(generally 401 or 422). However, you may want to customize what you return in
some situations. We can do that with the jwt_manager loader functions.

fromflaskimportFlask,jsonify,requestfromflask_jwt_extendedimport(JWTManager,jwt_required,create_access_token)app=Flask(__name__)app.config['JWT_SECRET_KEY']='super-secret'# Change this!jwt=JWTManager(app)# Using the expired_token_loader decorator, we will now call# this function whenever an expired but otherwise valid access# token attempts to access an endpoint@jwt.expired_token_loaderdefmy_expired_token_callback(expired_token):token_type=expired_token['type']returnjsonify({'status':401,'sub_status':42,'msg':'The {} token has expired'.format(token_type)}),401@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@app.route('/protected',methods=['GET'])@jwt_requireddefprotected():returnjsonify({'hello':'world'}),200if__name__=='__main__':app.run()

Here are the possible loader functions. Click on the links for a more
more details about what arguments your callback functions should expect
and what the return values of your callback functions need to be.

This can be useful if you have different use cases for different tokens.
For example, you might use short lived access tokens used in your web
application, but you allow the creation of long lived access tokens that other
developers can generate and use to interact with your api in their programs.
You could accomplish this like such: