FastAPI by Example: Cookie Authentication Scheme
Cookies are often used for session management. This code example demonstrates how to read and write cookies securely using the `Cookie` parameter and `Response` object.
Code
from fastapi import FastAPI, Cookie, Response
from typing import Annotated, Union
app = FastAPI()
@app.post("/login")
async def login(response: Response):
# Set a cookie
response.set_cookie(
key="session_id",
value="fake-session-id",
httponly=True, # Prevent JS access
secure=True, # Only send over HTTPS
samesite="lax" # CSRF protection
)
return {"message": "Cookie set"}
@app.get("/users/me")
async def read_current_user(
session_id: Annotated[Union[str, None], Cookie()] = None
):
if not session_id:
return {"message": "Not logged in"}
return {"session_id": session_id}
@app.post("/logout")
async def logout(response: Response):
# Delete cookie
response.delete_cookie("session_id")
return {"message": "Cookie deleted"}Explanation
Cookies are small pieces of data stored by the browser and sent with every request to the same domain. In FastAPI, you can read cookies using the Cookie parameter, which functions similarly to Query and Header parameters. However, to set or delete cookies, you must interact directly with the Response object, as cookies are part of the HTTP response headers.
Security is paramount when using cookies for authentication or session management. You should always set the httponly=True flag, which prevents client-side JavaScript from accessing the cookie, thereby mitigating the risk of Cross-Site Scripting (XSS) attacks. Additionally, the secure=True flag ensures that the cookie is only transmitted over encrypted HTTPS connections, protecting it from interception on insecure networks.
The samesite attribute is another critical security feature that helps protect against Cross-Site Request Forgery (CSRF) attacks. By setting it to "lax" or "strict", you control when the cookie is sent with cross-site requests. "lax" is a good default for most applications, allowing the cookie to be sent with top-level navigations while blocking it on third-party requests like images or frames.
Code Breakdown
response.set_cookie(...) attaches the Set-Cookie header to the response. This instructs the browser to store the value.httponly=True is a best practice for auth cookies. It means document.cookie in the browser will not show this cookie.Cookie() extracts the value from the Cookie header. If the cookie is missing, session_id will be None.response.delete_cookie(...) instructs the browser to remove the cookie by setting an expiration date in the past.
