@@ -218,7 +218,58 @@ The only real things to note here is the new @fresh_jwt_required decorator, and
218218the optional 'fresh=' keyword passed to the 'create_access_token' methods.
219219
220220### Changing Default Behaviors
221- TODO
221+ We provide what we think are sensible behaivors when attempting to access a protected
222+ endpoint. If the endpoint could not be used for any reason (missing/expired/invalid/etc
223+ access token) we will return json in the format of {'msg': <why accesing endpoint failed >}
224+ along with an appropiate http status code (generally 401 or 422). However, you may want
225+ to cusomize what is sent back in these cases. We can do that with the jwt_manager
226+ 'loader' functions.
227+ ``` python
228+ from flask import Flask, jsonify, request
229+ from flask_jwt_extended import JWTManager, jwt_required, create_access_token
230+
231+ app = Flask(__name__ )
232+ app.secret_key = ' super-secret' # Change this!
233+ jwt = JWTManager(app)
234+
235+
236+ @jwt.expired_token_callback
237+ def my_expired_token_callback ():
238+ return jsonify({
239+ ' status' : 401 ,
240+ ' sub_status' : 101 ,
241+ ' msg' : ' The token has expired'
242+ }), 200
243+
244+
245+ @app.route (' /login' , methods = [' POST' ])
246+ def login ():
247+ username = request.json.get(' username' , None )
248+ password = request.json.get(' password' , None )
249+ if username != ' test' and password != ' test' :
250+ return jsonify({" msg" : " Bad username or password" }), 401
251+
252+ ret = {' access_token' : create_access_token(username)}
253+ return jsonify(ret), 200
254+
255+
256+ @app.route (' /protected' , methods = [' GET' ])
257+ @jwt_required
258+ def protected ():
259+ return jsonify({' hello' : ' world' }), 200
260+
261+ if __name__ == ' __main__' :
262+ app.run()
263+ ```
264+ Now if an expired token tries to access the protected endpoint, we will get the
265+ json we specified back instead of our default behaivor.
266+
267+ The available loader functions are:
268+ * expired_token_loader
269+ * invalid_token_loader (function takes one arg, which is an error string of why its invalid)
270+ * unauthorized_loader
271+ * needs_fresh_token_loader
272+ * revoked_token_loader (see Blacklist and Token Revoking bellow)
222273
223274### Adding Custom Claims to the Access Token
224275TODO
0 commit comments