Sessions and Cookies, and When They Fit Better
A session signs a user in with a random id from secrets.token_urlsafe, kept in a sessions table and sent in an HttpOnly, Secure, SameSite cookie, so signing out deletes a row and takes effect at once, which suits one website on one server better than a token that stays valid until it expires.
Journeyman · FastAPI · REST API · Updated
After this lesson you can
- Sign a user in with a session, a random id from secrets.token_urlsafe saved in a sessions table and sent in an HttpOnly, Secure, SameSite cookie
- Sign a user out by deleting their session, and choose between sessions and tokens for an app
Key takeaways
- A token can't be taken back before it expires. A session can, because the server keeps a row for it, like a coat check keeps your coat.
- A session id is a long random value from secrets.token_urlsafe, saved in a sessions table with the user's id and when it expires.
- set_cookie with httponly=True, secure=True and samesite="lax" keeps the id away from the page's scripts, off plain HTTP, and out of most requests other sites start.
- Signing out deletes the session's row and the cookie, and the very next request with that id answers 401.
- Sessions fit one website on one server. Tokens fit phone apps, other servers and APIs called from many places.
Sign out of your bank's website on a library computer, and you expect to be out, right then. Many websites keep you signed in that way, with a session instead of a token. Knowing both lets you pick the right one for each app you build, and spot the wrong one in an app you join.
A token you can't take back
Tokens: Signing In with a JWT gave Bright Minds Study Group's students a token that's good for an hour. The server keeps no record of it: any request with a valid signature and a future exp gets in, which is what makes tokens stateless. That's also their weakness. If Maya signs in on a library computer and walks away, there's nothing the server can delete to sign her out: the token works until it expires.
A coat check works the other way round. You hand over your coat and get a ticket with a number. The number means nothing on its own; the coat stays behind the counter, and when the ticket is handed back, the coat is gone from the rack.
A session is that coat check. The server keeps a row for each signed-in user, and the browser holds only the ticket: a session id, a long random value. Deleting the row signs the user out at once.
A session id and a sessions table
The id must be impossible to guess, so it comes from Python's secrets module, made for exactly this, never from random:
import secrets
session_id = secrets.token_urlsafe(32)
print(len(session_id))
print(session_id == secrets.token_urlsafe(32))
43
False
token_urlsafe(32) takes 32 random bytes and writes them as 43 characters that are safe in a cookie. The second migration makes the table that holds each one, with whose it is and when it expires:
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
student_id INTEGER NOT NULL REFERENCES students (id) ON DELETE CASCADE,
expires_at TEXT NOT NULL
);
Sending it as a cookie
A cookie is a small value a website asks the browser to keep and send back with every request to that site. The sign-in route from Sign-Up and Sign-In Routes now saves a session and sets one:
SESSION_DAYS = 7
@router.post("/auth/sign-in", response_model=StudentOut)
def sign_in(body: SignIn, response: Response, conn: sqlite3.Connection = Depends(get_db, scope="function")):
student = students_data.find_student_by_email(conn, body.email)
if student is None or not password_hash.verify(body.password, student["password_hash"]):
raise HTTPException(status_code=401, detail="The email or password is wrong.")
session_id = secrets.token_urlsafe(32)
expires = datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)
students_data.add_session(conn, session_id, student["id"], expires.isoformat())
response.set_cookie(
"session", session_id, max_age=SESSION_DAYS * 24 * 60 * 60,
httponly=True, secure=True, samesite="lax",
)
return student
The answer carries this header (your id will differ):
set-cookie: session=XNh16R_pfajqi1l2TAoq3YuhSsNF4QTt7jVaAEW0zcs; HttpOnly; Max-Age=604800; Path=/; SameSite=lax; Secure
Each flag closes a door:
- HttpOnly: the page's own JavaScript can't read the cookie, so a harmful script slipped into the page can't steal the id.
- Secure: the browser sends it only over HTTPS, never over plain HTTP where anyone on the network could read it. (TestClient talks plain HTTP unless you give it
base_url="https://testserver".) - SameSite=Lax (read "same site, lax"): the browser leaves the cookie off most requests that another site starts, such as a hidden form on a stranger's page that posts to yours.
FastAPI reads the cookie back with Cookie, and the data module finds the student whose session hasn't expired:
@router.get("/me", response_model=StudentOut)
def me(session: str | None = Cookie(default=None), conn: sqlite3.Connection = Depends(get_db, scope="function")):
now = datetime.now(timezone.utc).isoformat()
student = students_data.student_for_session(conn, session, now)
if student is None:
raise HTTPException(status_code=401, detail="Sign in first.")
return student
def student_for_session(conn, session_id, now):
row = conn.execute(
"""SELECT students.id, students.name, students.email
FROM sessions JOIN students ON students.id = sessions.student_id
WHERE sessions.id = ? AND sessions.expires_at > ?""",
(session_id, now),
).fetchone()
return dict(row) if row else None
With Maya's cookie, GET /me answers {"id":1,"name":"Maya","email":"maya@example.com"}.
Signing out
Signing out deletes the row and tells the browser to drop the cookie:
@router.post("/auth/sign-out", status_code=204)
def sign_out(response: Response, session: str | None = Cookie(default=None), conn: sqlite3.Connection = Depends(get_db, scope="function")):
students_data.delete_session(conn, session)
response.delete_cookie("session", httponly=True, secure=True, samesite="lax")
It answers 204 No Content, and the very next GET /me with the old id answers 401 with "Sign in first.", even from a copy of the cookie: the coat is gone from the rack.
Sessions or tokens?
| What | Sessions | Tokens (JWT) |
|---|---|---|
| The server keeps | a row per signed-in user | nothing |
| Each request | looks the session up | checks a signature |
| Signing out | takes effect at once | waits for exp |
| Fits best | one website on one server | phone apps, other servers, APIs called from many places |
Choose sessions when your own web pages are the only caller, and tokens when apps and servers you don't run will call the API. Keep a token's life short, an hour as the study group's does, since it can't be taken back. You'll also meet Starlette's SessionMiddleware, which keeps the session's data inside a signed cookie instead of a table, so, like a token, a copy of the cookie keeps working until it expires.
Check yourself
2 questions to try on the lesson page.
So what
Tokens and sessions both answer "who is this?", and now you can choose the one that fits: a session when signing out must work at once, a token when many kinds of callers need in.