Partially protecting routesΒΆ

There may be cases where you want to use the same route regardless of if a JWT is present in the request or not. In these situations, you can use jwt_required() with the optional=True argument. This will allow the endpoint to be accessed regardless of if a JWT is sent in with the request.

If no JWT is present, get_jwt() and get_jwt_header(), will return an empty dictionary. get_jwt_identity(), current_user, and get_current_user() will return None.

If a JWT that is expired or not verifiable is in the request, an error will be still returned like normal.

from flask import Flask
from flask import jsonify
from flask import request

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

app = Flask(__name__)

# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = "super-secret"  # Change this!
jwt = JWTManager(app)


@app.route("/login", methods=["POST"])
def login():
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    if username != "test" or password != "test":
        return jsonify({"msg": "Bad username or password"}), 401

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token)


@app.route("/optionally_protected", methods=["GET"])
@jwt_required(optional=True)
def optionally_protected():
    current_identity = get_jwt_identity()
    if current_identity:
        return jsonify(logged_in_as=current_identity)
    else:
        return jsonify(logged_in_as="anonymous user")


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