0
0
FastapiHow-ToBeginner · 4 min read

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_age or expires: 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=True exposes the cookie to JavaScript, risking XSS attacks.
  • Forgetting to set secure=True in production allows cookies over HTTP, reducing security.
  • Not reading the cookie from Cookie dependency 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

ParameterDescriptionRecommended Value
keyName of the cookiee.g., "access_token"
valueValue stored in cookie (token)JWT or session token
httponlyPrevents JavaScript accessTrue
secureSend cookie only over HTTPSTrue in production
max_ageCookie lifetime in seconds3600 (1 hour) or as needed
pathCookie 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.