Skip to content

Conversation

@sharoonthomas
Copy link

Implements Option 2 from #5863.

Adds built-in CSRF protection using the Sec-Fetch-Site header that modern browsers send
automatically, with an Origin header fallback for older browsers.

Changes

  • Add CSRF_PROTECTION, CSRF_TRUSTED_ORIGINS, and CSRF_PROTECTED_METHODS config options
  • Add csrf_protection parameter to @app.route() and add_url_rule()
  • Add csrf_protection attribute support for class-based views
  • Check CSRF in full_dispatch_request() before preprocess_request()

Algorithm

  1. Allow safe methods (GET, HEAD, OPTIONS)
  2. Allow if origin is in CSRF_TRUSTED_ORIGINS
  3. If Sec-Fetch-Site header present: allow same-origin/none, reject
    same-site/cross-site
  4. If no browser headers present: allow (non-browser clients)
  5. If Origin present: allow if it matches Host, otherwise reject

Usage

# Enable globally
app.config['CSRF_PROTECTION'] = True

# Enable per-route
@app.route('/api', methods=['POST'], csrf_protection=True)
def api():
    ...

# Exempt a route when enabled globally
@app.route('/webhook', methods=['POST'], csrf_protection=False)
def webhook():
    ...

fixes #5863

@sharoonthomas sharoonthomas marked this pull request as ready for review December 17, 2025 03:00
@davidism
Copy link
Member

Are you using an LLM tool to substantially generate your writing or code?

@sharoonthomas
Copy link
Author

Are you using an LLM tool to substantially generate your writing or code?

Used claude code with opus 4.5 (substantially for the test cases).

@sharoonthomas
Copy link
Author

@ThiefMaster apologies if I've missed any contribution guidelines around tooling or process; happy to correct anything that's not aligned.

@davidism and @ThiefMaster If you have concerns about the implementation or approach itself, I'd genuinely like to hear them.

@davidism davidism closed this Dec 17, 2025
@davidism
Copy link
Member

You didn't have time to understand or implement the feature, but you expect the maintainers to have that time to carefully review everything you asked an LLM to generate. That's not acceptable for anything, but especially for a security-related feature.

If I did want to use an AI, I have access to the same tools you do, so you saved me essentially no time at all in that case.

@pallets pallets locked as off-topic and limited conversation to collaborators Dec 17, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Modern CSRF Protection Using Sec-Fetch-Site Header

2 participants