03 · Authentication Through a Session Cookie
In the previous tutorial, middleware wrapped the application:
Browser → middleware → router → route → middleware → browser
Today we’ll use middleware for something more consequential: maintaining a login session.
The complete flow becomes:
Login form → POST credentials → verify password → create session → set cookie → redirect → authenticated request
Authentication answers:
Who is making this request?
Authorization, which we’ll cover next, answers:
Is this authenticated user allowed to perform this particular action?
Those are related questions, but they are not the same question.
Today’s application
Section titled “Today’s application”This is a small, server-rendered application using:
- An ordinary HTML login form
- A hashed password
- Starlette’s
SessionMiddleware - A signed session cookie
- A protected dashboard
from typing import Annotated
from fastapi import FastAPI, Form, Requestfrom fastapi.responses import HTMLResponse, RedirectResponsefrom pwdlib import PasswordHashfrom starlette.middleware.sessions import SessionMiddleware
app = FastAPI()
app.add_middleware( SessionMiddleware, secret_key="replace-this-with-a-random-secret", session_cookie="app_session", same_site="lax", https_only=False,)
password_hash = PasswordHash.recommended()
users_by_username = { "max": { "id": 1, "username": "max", "password_hash": password_hash.hash("demo-password"), }}
dummy_hash = password_hash.hash("not-a-real-password")
def authenticate_user(username: str, password: str): user = users_by_username.get(username)
hash_to_check = ( user["password_hash"] if user else dummy_hash )
password_is_valid = password_hash.verify( password, hash_to_check, )
if not user or not password_is_valid: return None
return user
@app.get("/login", response_class=HTMLResponse)async def login_page(): return """ <html> <body> <h1>Log in</h1>
<form method="post" action="/login"> <label> Username: <input name="username"> </label>
<label> Password: <input name="password" type="password" > </label>
<button type="submit"> Log in </button> </form> </body> </html> """
@app.post("/login")def process_login( request: Request, username: Annotated[str, Form()], password: Annotated[str, Form()],): user = authenticate_user(username, password)
if user is None: return HTMLResponse( "<h1>Incorrect username or password</h1>", status_code=401, )
request.session.clear() request.session["user_id"] = user["id"]
return RedirectResponse( url="/dashboard", status_code=303, )
@app.get("/dashboard", response_class=HTMLResponse)async def dashboard(request: Request): user_id = request.session.get("user_id")
if user_id is None: return RedirectResponse( url="/login", status_code=303, )
return f""" <html> <body> <h1>Dashboard</h1> <p>Authenticated user ID: {user_id}</p> </body> </html> """This example is deliberately small. The users are still stored in a Python dictionary rather than SQLite, and the HTML is still written directly inside the routes rather than in Jinja templates.
The login handler uses ordinary def because password verification performs synchronous, relatively expensive work. FastAPI runs this handler in a worker thread. Calling the same helper directly inside an async def handler would occupy the event-loop thread; adding async does not move password hashing elsewhere.
The form above isolates the login and cookie lifecycle. A complete cookie-authenticated application also protects login and later writes against CSRF and limits repeated login attempts. Lesson 14 introduces the session-token pattern; same_site="lax" and a password field alone do not supply that whole protection.
We’ll replace those pieces later. For today, the important subject is the authentication flow.
Adding SessionMiddleware
Section titled “Adding SessionMiddleware”The application begins normally:
app = FastAPI()We then wrap it with session middleware:
app.add_middleware( SessionMiddleware, secret_key="replace-this-with-a-random-secret", session_cookie="app_session", same_site="lax", https_only=False,)SessionMiddleware provides a session dictionary associated with each browser.
Inside a route, that dictionary becomes available as:
request.sessionWithout SessionMiddleware, this would not work:
request.session["user_id"] = 1The middleware creates the session interface on the incoming side and handles the corresponding cookie on the outgoing side.
secret_key
Section titled “secret_key”secret_key="replace-this-with-a-random-secret"The secret key is used to cryptographically sign the session cookie.
The signature lets the application detect whether someone has modified the cookie.
Suppose the legitimate session says:
{"user_id": 1}A malicious user might try to change it to:
{"user_id": 999}But the attacker cannot produce a valid signature without knowing the server’s secret key. When the modified cookie returns, the middleware determines that the signature is invalid and refuses to accept the session.
The secret key in this example is only a placeholder. In production it should be:
- Long and randomly generated
- Stored in an environment variable or secrets system
- Excluded from Git
- Different between environments
If an attacker obtains the secret key, they may be able to forge valid session cookies.
session_cookie
Section titled “session_cookie”session_cookie="app_session"This controls the cookie’s name.
The browser will receive something resembling:
Set-Cookie: app_session=eyJ1c2VyX2lkIjogMX0...On later requests, the browser sends it back:
Cookie: app_session=eyJ1c2VyX2lkIjogMX0...The exact value will be longer because it includes encoded session data and a signature.
same_site
Section titled “same_site”same_site="lax"This restricts when the browser sends the cookie during requests originating from other websites.
"lax" is a practical default for many traditional server-rendered applications. It provides protection against many cross-site request forgery situations without preventing normal navigation to the website.
We will treat CSRF itself as a separate security subject later.
https_only
Section titled “https_only”https_only=FalseThis setting allows the browser to send the cookie over ordinary HTTP.
That is useful during local development at:
http://127.0.0.1:8000In production, it should normally be:
https_only=TrueThat gives the cookie the Secure attribute, instructing browsers to send it only through HTTPS connections.
Starlette describes SessionMiddleware as signed, cookie-based session support. Its session cookie is HttpOnly, which prevents ordinary browser JavaScript from reading it. (Starlette documentation)
Important: signed does not mean encrypted
Section titled “Important: signed does not mean encrypted”A signed cookie cannot be modified without invalidating its signature.
That does not necessarily mean its contents are secret.
A useful distinction is:
- Encryption: prevents people from reading data.
- Signing: reveals whether data has been modified.
Session data stored in this kind of cookie should therefore remain minimal and non-sensitive.
Good session data:
request.session["user_id"] = 1Bad session data:
request.session["password"] = "demo-password"request.session["social_security_number"] = "..."request.session["private_report"] = "..."Store an identifier in the session. Keep the sensitive and authoritative data in the database.
Password hashing
Section titled “Password hashing”We create a password-hashing utility:
password_hash = PasswordHash.recommended()PasswordHash.recommended() selects current recommended hashing settings from pwdlib.
FastAPI’s current security documentation uses pwdlib and recommends Argon2 for password hashing. (FastAPI password-hashing documentation)
The user dictionary contains:
"password_hash": password_hash.hash("demo-password")This line converts the plaintext password into a password hash.
The stored value will resemble:
$argon2id$v=19$m=65536,t=3,p=4$...The application does not need to recover the original password from this value.
When someone attempts to log in, the password library performs a verification operation:
password_hash.verify( submitted_password, stored_hash,)The library determines whether the submitted plaintext password corresponds to the stored hash.
Why hashing is not ordinary encryption
Section titled “Why hashing is not ordinary encryption”With encryption, possession of the correct key allows data to be decrypted.
Password hashes are designed to work differently. The application verifies a password without recovering the original password from the stored hash.
That means a real users table should contain:
password_hashand never:
passwordIn this tutorial, the hash is generated during startup only because we have not introduced the database yet.
In a real application, registration or an administrative process would generate the hash once, and SQLite would store it.
The authentication function
Section titled “The authentication function”def authenticate_user(username: str, password: str):This is an ordinary Python function.
It does not know anything about:
- HTTP
- Cookies
- Redirects
- HTML
- FastAPI routes
It receives two Python strings and returns either:
- A user
None
This is already the beginning of separating application logic from HTTP handling.
Looking up the user
Section titled “Looking up the user”user = users_by_username.get(username)If the submitted username is "max", the dictionary returns:
{ "id": 1, "username": "max", "password_hash": "...",}If the username does not exist, .get() returns:
NoneIt does not raise a KeyError.
Choosing a hash to verify
Section titled “Choosing a hash to verify”hash_to_check = ( user["password_hash"] if user else dummy_hash)This is a conditional expression.
If user exists:
hash_to_check = user["password_hash"]Otherwise:
hash_to_check = dummy_hashWhy verify the submitted password against a dummy hash when the username does not exist?
Because we do not want the application to behave radically differently depending on whether a username is valid.
A weaker implementation might do this:
if user is None: return None
password_hash.verify( password, user["password_hash"],)That skips the relatively expensive password verification when the username is unknown.
An attacker repeatedly measuring response times might detect a difference between:
- A username that exists
- A username that does not exist
Verifying against a dummy hash helps make both paths behave more similarly.
It is a small detail, but it illustrates a larger security principle:
Authentication code should avoid unintentionally revealing information about user accounts.
Verifying the password
Section titled “Verifying the password”password_is_valid = password_hash.verify( password, hash_to_check,)The first argument is the plaintext password submitted through the form.
The second is either:
- The real user’s stored password hash
- The dummy hash
The method returns a Boolean:
Trueor:
FalseThen:
if not user or not password_is_valid: return NoneAuthentication fails if either:
- The user does not exist
- The password does not match
Both situations produce the same outcome.
Finally:
return userA user object is returned only when the username exists and the password is valid.
At that moment, we have authenticated the credentials.
We have not yet created a login session.
Request one: displaying the login page
Section titled “Request one: displaying the login page”The browser first requests:
GET /login HTTP/1.1Host: 127.0.0.1:8000The request enters SessionMiddleware.
There may be no session cookie yet because this is the visitor’s first request.
The middleware passes the request deeper into the application, and the router matches:
@app.get("/login", response_class=HTMLResponse)FastAPI calls:
login_page()The function returns HTML containing:
<form method="post" action="/login">This tells the browser:
When this form is submitted, create a
POSTrequest to/login.
The two inputs have names:
<input name="username"><input name="password" type="password">Those names become the form-field names in the HTTP request.
The browser renders the page and waits for user input.
Request two: submitting credentials
Section titled “Request two: submitting credentials”Suppose the visitor enters:
Username: maxPassword: demo-passwordThe browser creates a new HTTP request:
POST /login HTTP/1.1Host: 127.0.0.1:8000Content-Type: application/x-www-form-urlencoded
username=max&password=demo-passwordThis is a completely separate request from GET /login.
HTTP does not keep the Python function from the previous request alive. The browser simply received HTML, displayed it, and later created another request.
The form data is encoded as:
username=max&password=demo-passwordIt is not JSON.
That is why the FastAPI route uses Form().
FastAPI reads the form
Section titled “FastAPI reads the form”The router matches:
@app.post("/login")The route signature is:
def process_login( request: Request, username: Annotated[str, Form()], password: Annotated[str, Form()],):FastAPI examines each parameter.
request: Request
Section titled “request: Request”request: RequestFastAPI supplies the current request object.
We need it because the session dictionary lives at:
request.sessionAnnotated[str, Form()]
Section titled “Annotated[str, Form()]”username: Annotated[str, Form()]This communicates two pieces of information.
First:
strThe route expects a Python string.
Second:
Form()FastAPI should retrieve the value from submitted form data rather than from:
- The URL path
- The query string
- A JSON body
- A request header
The same applies to:
password: Annotated[str, Form()]FastAPI parses the HTTP body and conceptually calls:
process_login( request=current_request, username="max", password="demo-password",)FastAPI recommends the Annotated form and requires Form() because HTML forms normally use application/x-www-form-urlencoded, not JSON. (FastAPI form documentation)
Authenticating the credentials
Section titled “Authenticating the credentials”Inside the route:
user = authenticate_user(username, password)The route hands the submitted values to our authentication function.
If the credentials are wrong, the function returns:
NoneThe route responds:
if user is None: return HTMLResponse( "<h1>Incorrect username or password</h1>", status_code=401, )The HTTP response would contain:
HTTP/1.1 401 UnauthorizedContent-Type: text/htmlNotice that the message is deliberately generic:
Incorrect username or passwordIt does not reveal whether "max" is a valid username.
If authentication succeeds, execution continues.
Creating the session
Section titled “Creating the session”request.session.clear()This removes any existing values from the current session.
Clearing the session during login helps prevent old session information from carrying into the newly authenticated state.
Then:
request.session["user_id"] = user["id"]The authenticated user’s ID is:
1The session dictionary now contains:
{"user_id": 1}An essential distinction:
The session does not prove the password again on every request.
The password was verified during login. The resulting signed session becomes the evidence presented on later requests.
That is what “staying logged in” means here.
Returning a redirect
Section titled “Returning a redirect”The login route returns:
return RedirectResponse( url="/dashboard", status_code=303,)This does not directly execute the dashboard route.
It creates an HTTP response resembling:
HTTP/1.1 303 See OtherLocation: /dashboardSet-Cookie: app_session=...The Location header tells the browser:
Make another request to
/dashboard.
The 303 status tells the browser to follow that location using GET.
This is useful after a form submission.
Without the redirect, refreshing the page might cause the browser to warn about resubmitting the login form.
The common flow is:
POST form ↓Process data ↓Return redirect ↓Browser makes GET requestThis is often called the Post/Redirect/Get pattern.
Where Set-Cookie comes from
Section titled “Where Set-Cookie comes from”Our route did not manually create this header:
Set-Cookie: app_session=...SessionMiddleware handles it.
Remember the middleware pattern:
# Incoming side
response = await call_next(request)
# Outgoing side
return responseWhen the request came inward, SessionMiddleware made this available:
request.sessionThe route then changed the session:
request.session["user_id"] = 1As the redirect response travels outward, the middleware sees the updated session. It serializes and signs the session data and adds the cookie to the response.
The flow is:
POST /login ↓SessionMiddleware opens session ↓Route verifies credentials ↓Route writes user_id into request.session ↓Route creates redirect response ↓SessionMiddleware signs session data ↓Middleware adds Set-Cookie ↓Browser receives responseThe browser stores the cookie under the rules included in Set-Cookie.
Request three: visiting the dashboard
Section titled “Request three: visiting the dashboard”The 303 redirect causes the browser to issue another request:
GET /dashboard HTTP/1.1Host: 127.0.0.1:8000Cookie: app_session=eyJ1c2VyX2lkIjogMX0...This request does not include the password.
It includes the session cookie.
That cookie is now the browser’s proof that a successful login occurred earlier.
Middleware reads the cookie
Section titled “Middleware reads the cookie”Before routing, SessionMiddleware:
- Finds the
app_sessioncookie. - Checks its cryptographic signature.
- Rejects it if the signature is invalid.
- Decodes the valid session data.
- makes the data available as
request.session.
Conceptually, the route receives:
request.session == {"user_id": 1}The router then selects:
@app.get("/dashboard")FastAPI calls:
dashboard(request=current_request)Checking the session
Section titled “Checking the session”The dashboard route begins:
user_id = request.session.get("user_id")If the visitor has a valid authenticated session:
user_id == 1If there is no valid login session:
user_id is NoneThe route checks that condition:
if user_id is None: return RedirectResponse( url="/login", status_code=303, )An unauthenticated visitor is sent back to the login page.
An authenticated visitor receives:
return f"""<html> <body> <h1>Dashboard</h1> <p>Authenticated user ID: {user_id}</p> </body></html>"""FastAPI creates the HTML response, which passes outward through the middleware and back to the browser.
The browser renders the dashboard.
Authentication is not authorization
Section titled “Authentication is not authorization”The dashboard currently asks only:
Does the session contain a user ID?That is an authentication check.
It identifies the requester as a logged-in user.
Now imagine the application has this route:
/admin/delete-user/42Knowing that the requester is user 1 is not sufficient.
The application must also determine:
Is user 1 an administrator?Or, in a document-review application:
Does this user belong to the firm that owns this document?Those are authorization questions.
A user can be:
- Authenticated but not authorized
- Authenticated and authorized
- Unauthenticated, so authorization cannot meaningfully succeed
The order is:
AuthenticationWho are you?
AuthorizationAre you allowed to do this?What will eventually change
Section titled “What will eventually change”Our application currently repeats the authentication check inside the dashboard:
user_id = request.session.get("user_id")
if user_id is None: return RedirectResponse(...)If twenty routes require login, we do not want to repeat that block twenty times.
We could place it in middleware, but then every route might require authentication, including /login itself and public pages.
FastAPI’s dependency system gives us a more precise approach:
current_user = Depends(get_current_user)That will let selected routes declare:
This route requires a current authenticated user.
Later, the dependency will:
- Read the session.
- Retrieve the user from SQLite through SQLAlchemy.
- Verify that the account still exists and is active.
- Return a proper user object.
- Stop the request if authentication fails.
For now, keeping the check inside one route makes the underlying mechanism visible.
The complete authentication lifecycle
Section titled “The complete authentication lifecycle”The full sequence spans three HTTP requests.
First request: show the form
Section titled “First request: show the form”Browser→ GET /login→ SessionMiddleware→ login_page()→ HTML response→ Browser renders formSecond request: process the login
Section titled “Second request: process the login”Browser submits username and password→ POST /login→ SessionMiddleware→ FastAPI parses form fields→ authenticate_user()→ Password hash verification→ user_id stored in request.session→ 303 redirect response→ SessionMiddleware signs session→ Set-Cookie header→ Browser stores cookieThird request: authenticated page
Section titled “Third request: authenticated page”Browser→ GET /dashboard with Cookie header→ SessionMiddleware verifies cookie signature→ Session data placed on request.session→ dashboard()→ Route reads user_id→ HTML response→ Browser renders dashboardThe browser never receives the stored password hash.
The server does not receive the plaintext password again when the dashboard is requested.
The session cookie connects the later request to the earlier successful login.
This is a signed client-side session. Clearing it removes the browser’s current cookie, but does not revoke every previously copied valid cookie. Applications that need immediate revocation can track sessions on the server or check a current account or session version on each request. That is a separate decision from signing the cookie.
The central idea
Section titled “The central idea”Authentication is not one permanent connection between the browser and a Python function.
It is a sequence of otherwise independent HTTP requests.
The application creates continuity by giving the browser a signed cookie. The browser presents that cookie on later requests, and middleware reconstructs the session before the route runs.
That gives us the new lifecycle:
Browser sends cookie ↓Middleware verifies and decodes session ↓Route identifies the user ↓Application performs its work ↓Middleware maintains the session ↓Browser receives the responseIn the next tutorial, we’ll add authorization and make the distinction concrete: two users may both be correctly authenticated, while only one is permitted to access a particular document.