python
50 lines · 7 steps
JWT bearer auth as a FastAPI dependency
A reusable dependency that validates a bearer token and hands routes a typed current user.
Explained by
highlit
1import os
2from datetime import datetime, timezone
3
4import jwt
5from fastapi import Depends, HTTPException, status
6from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
7from pydantic import BaseModel
8
9JWT_SECRET = os.environ["JWT_SECRET"]
10JWT_ALGORITHM = "HS256"
11JWT_AUDIENCE = "api://internal"
12
13bearer_scheme = HTTPBearer(auto_error=True)
14
15
16class CurrentUser(BaseModel):
17 id: str
18 email: str
19 scopes: list[str] = []
20
21
22def get_current_user(
23 credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme),
24) -> CurrentUser:
25 try:
26 payload = jwt.decode(
27 credentials.credentials,
28 JWT_SECRET,
29 algorithms=[JWT_ALGORITHM],
30 audience=JWT_AUDIENCE,
31 options={"require": ["exp", "sub"]},
32 )
33 except jwt.ExpiredSignatureError:
34 raise HTTPException(
35 status_code=status.HTTP_401_UNAUTHORIZED,
36 detail="Token has expired",
37 headers={"WWW-Authenticate": "Bearer"},
38 )
39 except jwt.InvalidTokenError:
40 raise HTTPException(
41 status_code=status.HTTP_401_UNAUTHORIZED,
42 detail="Could not validate credentials",
43 headers={"WWW-Authenticate": "Bearer"},
44 )
45
46 return CurrentUser(
47 id=payload["sub"],
48 email=payload.get("email", ""),
49 scopes=payload.get("scopes", []),
50 )
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Modeling auth as a dependency lets any route request the current user by declaring a single parameter.
- 2Verifying signature, algorithm, audience, and required claims together closes off common JWT forgery vectors.
- 3Translating decode failures into 401s with a WWW-Authenticate header keeps the API's auth contract explicit.
Related explainers
python
class Parser: def __init__(self, text): self.tokens = self._tokenize(text) self.pos = 0
A recursive descent arithmetic parser
recursive-descent
tokenizer
operator-precedence
Intermediate
9 steps
rust
use axum::{ extract::{FromRef, FromRequestParts}, http::{header, request::Parts, StatusCode}, RequestPartsExt,
How a JWT extractor works in Axum
jwt
authentication
extractors
Intermediate
8 steps
typescript
import { InjectionToken, inject, Provider, isDevMode } from '@angular/core'; import { WINDOW } from './window.token'; export interface AnalyticsConfig {
Layered config with an Angular InjectionToken
dependency-injection
configuration
factory-provider
Intermediate
8 steps
python
import re from dataclasses import dataclass, field
Building a table of contents from Markdown
regular-expressions
parsing
slugification
Intermediate
9 steps
javascript
const IBAN_LENGTHS = { DE: 22, FR: 27, GB: 22, ES: 24, IT: 27, NL: 18, BE: 16, CH: 21, AT: 20, PT: 25, };
How IBAN validation works in JavaScript
validation
checksum
modular-arithmetic
Intermediate
8 steps
python
from flask import Blueprint, render_template, redirect, url_for, session, request from wtforms import Form, StringField, SelectField, IntegerField from wtforms.validators import DataRequired, Email, NumberRange
A multi-step signup wizard in Flask
blueprints
session-state
form-validation
Intermediate
10 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/jwt-bearer-auth-as-a-fastapi-dependency-explained-python-d8bd/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.