📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials Flask Web Framework Flask JWT Auth

Flask JWT Auth

6 min read Quiz at the end
Secure Flask APIs with JWT tokens using Flask-JWT-Extended: create, protect routes, get identity.

JWT Authentication

pip install flask-jwt-extended

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

jwt = JWTManager(app)
app.config["JWT_SECRET_KEY"]         = "super-secret"
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=1)

@api.route("/login")
class Login(Resource):
    def post(self):
        email    = request.json.get("email")
        password = request.json.get("password")
        user = User.query.filter_by(email=email).first()
        if not user or not user.check_password(password):
            return {"message": "Invalid credentials"}, 401
        return {
            "access_token":  create_access_token(identity=user.id),
            "refresh_token": create_refresh_token(identity=user.id),
        }

@api.route("/me")
class Me(Resource):
    @jwt_required()
    def get(self):
        user_id = get_jwt_identity()
        return db.session.get(User, user_id).to_dict()
Topic Quiz · 2 questions

Test your understanding before moving on

1. What does JWT stand for?
💡 JWT stands for JSON Web Token — a compact self-contained token for auth.
2. What does @jwt_required() do?
💡 @jwt_required() validates the Bearer token and returns 401 if invalid.