Simple CSRF protection using nginx alone

architecture, csrf, csrf-protection, security, xss

Solution

The point of CSRF tokens is to require attackers to read a value from your domain in order to send requests.

Therefore, you can have a separate endpoint in the API that simply returns a CSRF form token.

Attackers will not be able to read the token due to the same-origin policy (for the same reason that they can't read a token from HTML source), so you will be safe. This has the disadvantage of requiring an extra HTTP request.

Also, make sure that the response is not valid Javascript, or attackers can run it as a `<script>` tag and use prototype & property tricks to read the value

Problem

I have an nginx server serving plain HTML and JS files. The js code then calls various REST API to GET/POST data from API servers. If nginx receives a request for /api/ location, it forwards the request to another server which handles all the APIs. This api server is built in Ruby on Rails. Since all my plain HTML pages are delivered by nginx directly, I cant have server side sessions while they are rendered. What can I do to prevent CSRF attacks?

Original source