How to avoid third-party CSRF cookies when embedding snippets from Opengist
While integrating Opengist to serve code snippets in the blog, I discovered that everytime a snippet is loaded a _csrf cookie is set by Opengist.
This is not very cool, and I've found a way to prevent this using nginx.
Why is this _csrf cookie not cool on embedded code snippets?
- It is not necessary (as the embedded code snippet does not provide any links/actions to perform on the Opengist instance where CSRF protection would be needed).
- It sets a third-party cookie for everyone visiting the blog.
- It breaks caching of the embedded code snippets on browser side (as the cookie is updated on every request).
How did I prevent the _csrf cookie with nginx?
I'm using the following (simplified) nginx reverse proxy config in front of the Opengist docker container.
It has a conditional if
section where the headers-more-nginx-module is used to remove the Set-Cookie HTTP header, on the responses for the embedded code snippets.
The if
condition is specific to my username and will need to be adjusted to your setup of course.
server { server_name gist.x-way.org; location / { if ( $uri ~* ^/x-way/[0-9a-fA-F]+\.js$ ) { more_clear_headers "Set-Cookie"; } proxy_pass http://127.0.0.1:6157; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
This is a quite ugly hack.
I submitted a pull-request for Opengist to exclude the embedded code snippets from the CSRF middleware.
Let's see where this leads 🤞