CVE-2021-32677 Overview
CVE-2021-32677 is a Cross-Site Request Forgery (CSRF) vulnerability affecting FastAPI, a popular web framework for building APIs with Python 3.6+ based on standard Python type hints. FastAPI versions lower than 0.65.2 that used cookies for authentication in path operations receiving JSON payloads sent by browsers were vulnerable to this attack.
The vulnerability exists because FastAPI would incorrectly parse request payloads as JSON even when the content-type header was not set to application/json or a compatible JSON media type. This behavior allowed attackers to craft malicious requests with a text/plain content type containing JSON data, which browsers would execute immediately without CORS preflight checks, including cookies in the request.
Critical Impact
Attackers can perform unauthorized actions on behalf of authenticated users by exploiting the improper content-type validation, potentially leading to data theft or manipulation of user accounts.
Affected Products
- tiangolo FastAPI versions prior to 0.65.2
- Fedora Project Fedora 34
Discovery Timeline
- 2021-06-09 - CVE CVE-2021-32677 published to NVD
- 2024-11-21 - Last updated in NVD database
Technical Details for CVE-2021-32677
Vulnerability Analysis
This CSRF vulnerability exploits a fundamental flaw in how FastAPI handled content-type validation for incoming requests. The core issue lies in the framework's permissive parsing behavior that accepted JSON data regardless of the declared content type in the request header.
When a browser sends a request with content-type: text/plain, CORS (Cross-Origin Resource Sharing) policies classify it as a "Simple request" that does not require a preflight OPTIONS request. This means the browser will immediately execute the request and include any cookies associated with the target domain.
By crafting a malicious webpage that sends a text/plain request containing a JSON payload to a vulnerable FastAPI endpoint, an attacker could execute authenticated actions on behalf of a logged-in user without their knowledge or consent. The impact includes potential unauthorized data access and modification of sensitive information.
Root Cause
The root cause of this vulnerability is improper input validation in FastAPI's request handling logic. The framework failed to verify that the content-type header matched application/json or another JSON-compatible media type (such as application/geo+json) before attempting to parse the request body as JSON. This allowed requests with arbitrary content types to be processed as if they were legitimate JSON API calls.
Attack Vector
The attack exploits the combination of browser CORS policies and FastAPI's permissive content-type handling. An attacker hosts a malicious webpage that, when visited by an authenticated user, automatically sends a cross-origin request to the vulnerable FastAPI application. The request uses content-type: text/plain to bypass CORS preflight requirements while including a JSON payload that FastAPI incorrectly processes.
The attack requires user interaction (visiting the malicious page) while the victim is authenticated to the target application using cookie-based sessions.
# Security patch in fastapi/routing.py - adds content-type validation
import asyncio
+import email.message
import enum
import inspect
import json
Source: GitHub Commit Update
The patch introduces proper content-type header checking using Python's email.message module to validate that incoming requests declare a JSON-compatible media type before parsing the body as JSON.
Detection Methods for CVE-2021-32677
Indicators of Compromise
- Unusual cross-origin requests to API endpoints with text/plain content type containing JSON-structured data
- State-changing API operations originating from unexpected referrer domains
- Authentication cookie usage in requests with non-JSON content types
- Server logs showing successful JSON parsing for requests with text/plain or other non-JSON content types
Detection Strategies
- Monitor web server access logs for POST/PUT/DELETE requests with content-type: text/plain or other non-JSON content types to API endpoints
- Implement Web Application Firewall (WAF) rules to flag requests where the body appears to be JSON but the content-type header is not application/json
- Review application logs for authenticated API operations that lack proper referrer headers or originate from external domains
- Audit FastAPI dependencies to identify installations running versions below 0.65.2
Monitoring Recommendations
- Deploy logging to capture and alert on content-type mismatches in API requests
- Implement SIEM rules to correlate cross-origin request patterns with sensitive API operations
- Monitor for anomalous patterns of authenticated API calls, particularly those modifying user data or permissions
- Use dependency scanning tools to maintain visibility into FastAPI version deployments across your environment
How to Mitigate CVE-2021-32677
Immediate Actions Required
- Upgrade FastAPI to version 0.65.2 or later immediately
- Audit all FastAPI deployments to identify affected versions
- Review API endpoints that use cookie-based authentication for potential exposure
- Consider temporarily implementing additional CSRF protections while upgrading
Patch Information
The vulnerability is fixed in FastAPI version 0.65.2. The fix ensures that request data is parsed as JSON only when the content-type header is explicitly set to application/json or another JSON-compatible media type like application/geo+json.
For detailed patch information, refer to the GitHub Commit Update and the GitHub Security Advisory.
Workarounds
- Implement a custom middleware that validates the content-type header and rejects requests that attempt to send JSON data without a proper JSON content type
- Add a dependency to affected path operations that checks the content-type header and aborts the request if it is not application/json or another JSON-compatible content type
- Implement additional CSRF token validation for state-changing operations
- Consider migrating from cookie-based authentication to header-based authentication tokens for API endpoints
# Example middleware workaround for content-type validation
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
@app.middleware("http")
async def validate_content_type(request: Request, call_next):
if request.method in ["POST", "PUT", "PATCH", "DELETE"]:
content_type = request.headers.get("content-type", "")
if request.headers.get("content-length", "0") != "0":
if not content_type.startswith("application/json"):
raise HTTPException(
status_code=415,
detail="Unsupported Media Type"
)
return await call_next(request)
Disclaimer: This content was generated using AI. While we strive for accuracy, please verify critical information with official sources.


