Protecting a RESTful JSON API from a CSRF attack
“Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated” (OWASP definition)
CSRF is related to Cross-Site Scripting (XSS), but does not require the execution of Javascript or any other front-end code. In fact, APIs are increasingly vulnerable to CSRF attacks due to the emergence of single-page web applications. A single-page web application is a Javascript “client” application that executes in the user’s browser. The client application interchanges data with the server via API calls. There are many advantages to this architecture, but it does increase the attack surface for CSRF attacks. When the user authenticates, they receive a unique token with a limited lifetime, which is usually stored as a cookie. The token is passed to the server as a header on every API call, and the server may return a new token with an updated expiration time with every response.