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
javascript
import { parsePhoneNumberFromString } from 'libphonenumber-js'; export class PhoneValidationError extends Error { constructor(message, code) {
Normalizing phone numbers with typed errors
validation
error-handling
custom-errors
Intermediate
6 steps
typescript
import { Injectable, computed, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs';
Optimistic updates with Angular signals
signals
optimistic-updates
state-management
Intermediate
9 steps
rust
use std::error::Error; use std::path::Path; use serde::Deserialize;
Custom CSV deserialization with serde in Rust
serde
csv
deserialization
Intermediate
7 steps
go
package config import ( "fmt"
Loading typed config from environment variables in Go
configuration
environment-variables
type-parsing
Beginner
8 steps
php
public function importCustomers(UploadedFile $file): array { $errors = []; $imported = 0;
Validating a CSV import in Laravel
csv-parsing
validation
error-accumulation
Intermediate
8 steps
javascript
const express = require('express'); const { z } = require('zod'); const router = express.Router();
Validating query params with Zod in Express
validation
schema-parsing
query-building
Intermediate
9 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.