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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Decorators let you enforce auth as a reusable gate that wraps any view without touching its body.
- 2Returning a JSON payload plus a 401 status short-circuits the request before the protected handler ever runs.
- 3Flask's request-scoped g object is the idiomatic place to hand the authenticated user to downstream code.
Related explainers
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-a-jwt-auth-decorator-works-in-flask-explained-python-4753/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.