Securing a go REST API - Part 4: CSRF

This is part 4 of a multipart series on how to secure your API in golang. This post will talk about dealing with Cross-Site Request Forgery (CSRF in short), an attack on web applications where the attacker tricks users into performing unintended actions. This attack only works for APIs served to a frontend (e.g. a React application), as it is based on the fact that browsers send the user’s cookies automatically when calling a web page.

Essentially, you need to serve your user a CSRF Token, a secret the client needs to include in the API every time a state-changing request is made. For requests that never change the state and just retrieve information, nothing needs be done. Since “roll your own” is not a good idea (in terms of security), I would recommend using the excellent library gorilla/csrf.

In REST APIs you would usually send your client either through a header or as part of the body. If you send the token in the request body, make sure that each response contains a different CSRF token, otherwise you might be susceptible to the BREACH attack. Using gorilla/csrf, this is as easy as calling csrf.Token(r) for each response.

If you want to read up on CSRF an other prevention techniques, I recommend the OWASP Cheat Sheet.