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 flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
typescript
import { Injectable, UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { ConfigService } from '@nestjs/config';
How a JWT strategy authenticates in NestJS
authentication
jwt
passport
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 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.