JWT Authentication (Flask)

JWT (JSON Web Token) authentication in Flask issues a signed token after login that the client sends on each API request (usually in an Authorization: Bearer header). The server verifies the token's signature instead of using cookie sessions.

Flask

APIs are often stateless and consumed by mobile apps or other servers, where cookie sessions are awkward. A JWT packs the user's identity and an expiry into a compact, signed token: the client stores it and presents it on each request, and the server trusts it after verifying the signature with its secret.

In Flask, extensions like Flask-JWT-Extended handle the heavy lifting: create_access_token(identity=user.id) issues a token at login, the @jwt_required() decorator protects endpoints, and get_jwt_identity() returns the current user's id inside a protected view.

Because a JWT is only signed, not encrypted, never put secrets in its payload, and keep access tokens short-lived (with refresh tokens for renewal). Treat the signing secret like a password, and pair JWT APIs with CORS and HTTPS.

Syntax

@jwt_required()
def protected(): get_jwt_identity()

Examples

Python

from flask_jwt_extended import (JWTManager, create_access_token,
                                jwt_required, get_jwt_identity)

app.config["JWT_SECRET_KEY"] = "change-me"
jwt = JWTManager(app)

@app.route("/login", methods=["POST"])
def login():
    token = create_access_token(identity="user-1")
    return jsonify(access_token=token)

@app.route("/me")
@jwt_required()
def me():
    return jsonify(user=get_jwt_identity())

Learn it in a lesson

See also

Back to the Dictionary