Changing Default Behaviors¶

This extension provides sensible default behaviors. For example, if an expired token attempts to access a protected endpoint, you will get a JSON response back like {"msg": "Token has expired"} and a 401 status code. However there may be various behaviors of this extension that you want to customize to your application’s needs. We can do that with the various loader functions. Here is an example of how to do that.

from flask import Flask
from flask import jsonify

from flask_jwt_extended import create_access_token
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager

app = Flask(__name__)

app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)


# Set a callback function to return a custom response whenever an expired
# token attempts to access a protected route. This particular callback function
# takes the jwt_header and jwt_payload as arguments, and must return a Flask
# response. Check the API documentation to see the required argument and return
# values for other callback functions.
@jwt.expired_token_loader
def my_expired_token_callback(jwt_header, jwt_payload):
    return jsonify(code="dave", err="I can't let you do that"), 401


@app.route("/login", methods=["POST"])
def login():
    access_token = create_access_token("example_user")
    return jsonify(access_token=access_token)


@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
    return jsonify(hello="world")


if __name__ == "__main__":
    app.run()

There are all sorts of callbacks that can be defined to customize the behaviors of this extension. See the Configuring Flask-JWT-Extended API Documentation for a full list of callback functions that are available in this extension.