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
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
python
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
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/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.