How to Use HttpOnly Cookie for Authentication in FastAPI
In FastAPI, you set an
HttpOnly cookie by using the Response.set_cookie() method with the httponly=True flag during login. This cookie stores the authentication token securely, preventing JavaScript access and enhancing security for user sessions.Syntax
To set an HttpOnly cookie in FastAPI, use the set_cookie method on the Response object with these key parameters:
key: The cookie name.value: The cookie value, usually a token.httponly=True: Prevents JavaScript access to the cookie.max_ageorexpires: Optional, sets cookie lifetime.secure: Optional, ensures cookie sent only over HTTPS.
python
response.set_cookie(key="access_token", value=token, httponly=True, max_age=3600, secure=True)
Example
This example shows a FastAPI login endpoint that sets an HttpOnly cookie with a JWT token. The cookie is then used for authentication in a protected route.
python
from fastapi import FastAPI, Response, Depends, HTTPException, status, Cookie from fastapi.security import OAuth2PasswordRequestForm from typing import Optional app = FastAPI() fake_users_db = {"user1": "password1"} # Dummy function to create a token def create_token(username: str) -> str: return f"token-for-{username}" @app.post("/login") def login(response: Response, form_data: OAuth2PasswordRequestForm = Depends()): username = form_data.username password = form_data.password if fake_users_db.get(username) != password: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials") token = create_token(username) response.set_cookie(key="access_token", value=token, httponly=True, max_age=3600, secure=False) return {"message": "Logged in"} @app.get("/protected") def protected_route(access_token: Optional[str] = Cookie(None)): if access_token is None or not access_token.startswith("token-for-"): raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authenticated") return {"message": f"Hello, your token is {access_token}"}
Output
POST /login with valid credentials sets HttpOnly cookie 'access_token'.
GET /protected reads cookie and returns greeting with token.
Common Pitfalls
- Not setting
httponly=Trueexposes the cookie to JavaScript, risking XSS attacks. - Forgetting to set
secure=Truein production allows cookies over HTTP, reducing security. - Not reading the cookie from
Cookiedependency in protected routes causes authentication failures. - Using cookies without CSRF protection can be risky; consider CSRF tokens if needed.
python
from fastapi import Response # Wrong: Missing httponly response.set_cookie(key="token", value="abc123") # Right: Set httponly response.set_cookie(key="token", value="abc123", httponly=True)
Quick Reference
| Parameter | Description | Recommended Value |
|---|---|---|
| key | Name of the cookie | e.g., "access_token" |
| value | Value stored in cookie (token) | JWT or session token |
| httponly | Prevents JavaScript access | True |
| secure | Send cookie only over HTTPS | True in production |
| max_age | Cookie lifetime in seconds | 3600 (1 hour) or as needed |
| path | Cookie path scope | "/" for whole site |
Key Takeaways
Always set httponly=True when setting auth cookies to protect from JavaScript access.
Use secure=True in production to send cookies only over HTTPS.
Read cookies in FastAPI routes using the Cookie dependency.
Set appropriate max_age to control cookie expiration.
Consider CSRF protection when using cookies for authentication.