get_current_user dependency that protects routes, and role-based access control (RBAC) that restricts specific endpoints to admin users. Every piece follows the pattern used in production FastAPI applications.
Authentication Models Compared
- JWT (Recommended for APIs)
- Session-Based
- HTTP Basic
The server issues a signed token at login. The client stores it and sends it with every subsequent request. The server verifies the signature — no database lookup needed per request.Best for: REST APIs, SPAs, mobile apps, microservices.
Advantage: Stateless, scales horizontally with no shared session storage.
What is a JWT?
A JSON Web Token is a compact, URL-safe string containing signed claims (statements about a user) that the server can verify without querying a database. A JWT has three dot-separated parts:- Header — algorithm (
HS256) and token type (JWT), Base64URL-encoded. - Payload — claims:
sub(subject/user ID),exp(expiry),role, and any other data you include. - Signature —
HMAC(base64(header) + "." + base64(payload), SECRET_KEY). Any change to the header or payload invalidates the signature.
JWT Authentication Lifecycle
Step-by-Step Implementation
Step 1: Install Dependencies
Step 2: User Model
Step 3: Password Hashing
Never store plain-text passwords. Use bcrypt to hash on registration and verify at login:Step 4: Token Generation
Step 5: Registration and Login Endpoints
Step 6: Bearer Token Verification Dependency
This dependency extracts the JWT from theAuthorization: Bearer <token> header, verifies its signature and expiry, and returns the authenticated user:
Step 7: Protecting Routes
Applyget_current_user to any endpoint that requires authentication:
Step 8: Role-Based Access Control (RBAC)
Use a dependency factory to restrict endpoints to specific roles:Testing in Swagger UI
1
Open Swagger UI
Navigate to
http://127.0.0.1:8000/docs.2
Register a user
Use
POST /auth/register to create a test user.3
Log in and copy the token
Use
POST /auth/login with your credentials. Copy the access_token value from the JSON response.4
Authorise in Swagger
Click the green Authorize 🔒 button at the top of the page. Paste your token in the value field and click Authorize.
5
Call protected endpoints
Now call
/profile or any protected route — Swagger will automatically include the Authorization: Bearer <token> header.