Setting the HttpOnly attribute on cookies prevents client-side scripts from reading their values, limiting the damage that cross-site scripting (XSS) attacks can cause.

Why is this an issue?

When a cookie is created without the HttpOnly attribute, or with it explicitly set to false, client-side scripts running in the browser can read the cookie’s value. By default, cookies are created with HttpOnly set to false, meaning they are accessible to browser scripts unless the developer explicitly enables this protection. Setting HttpOnly to true instructs the browser to block script access to the cookie, limiting the damage from XSS attacks that attempt to steal session credentials.

What is the potential impact?

Session hijacking and account takeover

The most common target of cookie theft is the session cookie used to authenticate a user. If an attacker can exploit an XSS vulnerability on a page where a session cookie is accessible to scripts, they can steal it and use it to impersonate the authenticated user without needing their credentials. This can lead to unauthorized access to sensitive account data, account takeover, and potential privilege escalation within the application.

How to fix it in Flask

Code examples

The following code creates a cookie without enabling the HttpOnly attribute.

Noncompliant code example

from flask import Response

@app.route('/')
def index():
    response = Response()
    response.set_cookie('key', 'value')  # Noncompliant
    return response

Compliant solution

from flask import Response

@app.route('/')
def index():
    response = Response()
    response.set_cookie('key', 'value', httponly=True)
    return response

How to fix it in FastAPI

Code examples

The following code creates a cookie without enabling the HttpOnly attribute.

Noncompliant code example

from fastapi import FastAPI, Response

app = FastAPI()

@app.get('/')
async def index(response: Response):
    response.set_cookie('key', 'value')  # Noncompliant
    return {"message": "Hello world!"}

Compliant solution

from fastapi import FastAPI, Response

app = FastAPI()

@app.get('/')
async def index(response: Response):
    response.set_cookie('key', 'value', httponly=True)
    return {"message": "Hello world!"}

Resources

Documentation

Standards