python 41 lines · 6 steps

How a JWT auth decorator works in Flask

A reusable decorator that validates a Bearer token and attaches the current user before any protected view runs.

Explained by highlit
1from functools import wraps
2 
3import jwt
4from flask import current_app, g, jsonify, request
5 
6from .models import User
7 
8 
9def require_auth(f):
10 @wraps(f)
11 def decorated(*args, **kwargs):
12 auth = request.headers.get("Authorization", "")
13 
14 if not auth.startswith("Bearer "):
15 return jsonify(error="authentication_required",
16 message="Missing or malformed Authorization header"), 401
17 
18 token = auth[7:].strip()
19 
20 try:
21 payload = jwt.decode(
22 token,
23 current_app.config["JWT_SECRET"],
24 algorithms=["HS256"],
25 )
26 except jwt.ExpiredSignatureError:
27 return jsonify(error="token_expired",
28 message="Access token has expired"), 401
29 except jwt.InvalidTokenError:
30 return jsonify(error="invalid_token",
31 message="Access token is invalid"), 401
32 
33 user = User.query.get(payload.get("sub"))
34 if user is None or not user.is_active:
35 return jsonify(error="invalid_token",
36 message="User no longer exists or is disabled"), 401
37 
38 g.current_user = user
39 return f(*args, **kwargs)
40 
41 return decorated
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Decorators let you enforce auth as a reusable gate that wraps any view without touching its body.
  2. 2Returning a JSON payload plus a 401 status short-circuits the request before the protected handler ever runs.
  3. 3Flask's request-scoped g object is the idiomatic place to hand the authenticated user to downstream code.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How a JWT auth decorator works in Flask — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code