maxcountryman / flask-seasurf

SeaSurf is a Flask extension for preventing cross-site request forgery (CSRF).
http://readthedocs.org/docs/flask-seasurf/
Other
190 stars 49 forks source link

Send Set-Cookie header(much) less often to reduce breaking cache #71

Closed jesseops closed 7 years ago

jesseops commented 7 years ago

The current behavior of Flask-SeaSurf causes it to send a Set-Cookie header on every request unless the view function is wrapped in @csrf.exempt or SEASURF_INCLUDE_OR_EXEMPT_VIEWS is set to include.

This unfortunately breaks caching. For example, Nginx will not cache requests with the Vary or Set-Cookie headers. This is bad for frequent AJAX GET requests that have no need of the CSRF Token(as one example).

Django gets around this issue by checking to see if the CSRF Token shows up in the request cookies, and checking to see if a token was requested by the template. If explicitly requested (ie by including {% csrf_token %} in the template or the CSRF Token in the cookie does not match (non-existent or invalid), the middleware will add the Set-Cookie header.

This pull request adds that behavior with clear documentation of what it's doing, as well as adding tests to verify the behavior.

maxcountryman commented 7 years ago

Thank you for this!

jesseops commented 7 years ago

Any chance this will get merged soon?

alanhamlett commented 7 years ago

LGTM

jesseops commented 7 years ago

I've currently repackaged this in our internal PyPi repository in order to mitigate the caching concern while waiting for this to make it into a flask-seasurf release. I'll keep an eye here so we can swap back to the official package once this is merged. Thanks!