Flask-JWT-Extended

4.7.1 · active · verified Thu Apr 09

Flask-JWT-Extended is a Python library that provides extended JWT (JSON Web Token) integration for Flask applications. It simplifies the process of adding JWT-based authentication to your API, handling token creation, authorization, and common features like fresh tokens, blocklists, and token refreshing. The current version is 4.7.1, and it maintains a steady release cadence with active development and regular updates to support new Python and Flask versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Flask-JWT-Extended, create a login endpoint to issue an access token, and protect another endpoint using the `@jwt_required()` decorator. It shows how to retrieve the identity of the authenticated user within a protected route. Remember to set the `FLASK_JWT_SECRET_KEY` environment variable for production environments.

import os
from flask import Flask, jsonify, request
from flask_jwt_extended import create_access_token, jwt_required, JWTManager, get_jwt_identity

app = Flask(__name__)
# Set a secret key for JWT signing. For production, use a strong, unique key.
app.config["JWT_SECRET_KEY"] = os.environ.get("FLASK_JWT_SECRET_KEY", "super-secret-dev-key")

# Initialize the Flask-JWT-Extended extension
jwt = JWTManager(app)

# A simple login route to get an access token
@app.route("/login", methods=["POST"])
def login():
    username = request.json.get("username", None)
    password = request.json.get("password", None)

    # In a real application, you'd verify these credentials against a database
    if username != "testuser" or password != "testpass":
        return jsonify({"msg": "Bad username or password"}), 401

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

# A protected route that requires a valid JWT access token
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
    # Access the identity of the current user with get_jwt_identity
    current_user = get_jwt_identity()
    return jsonify(logged_in_as=current_user), 200

if __name__ == "__main__":
    # To run:
    # 1. Set FLASK_JWT_SECRET_KEY environment variable (or it will use 'super-secret-dev-key')
    #    e.g., export FLASK_JWT_SECRET_KEY="your-strong-secret"
    # 2. Run this script: python your_app.py
    # 3. Test with curl:
    #    curl -X POST -H "Content-Type: application/json" -d '{"username":"testuser", "password":"testpass"}' http://127.0.0.1:5000/login
    #    (Copy the access_token from the response)
    #    curl -H "Authorization: Bearer <your_access_token>" http://127.0.0.1:5000/protected
    app.run(debug=True)

view raw JSON →