﻿One classic attack when working with web applications is Cross Site Request Forgery aka CSRF/XSRF (read C-Surf). They are used by attackers to perform requests on behalf of users in your application without them noticing. Let’s look at how they can pull this off and how we can protect our applications from these type of threat.

Let’s talk theory

Before we can prevent CSRF attacks we need to understand how they work. Typically these attacks are executed on the functionality of web applications that use form-based submissions like POST requests and cookie-based authentication.

An attacker places a hidden form into their malicious page that automatically performs a POST request to your page’s endpoint. The browser then automatically sends all the cookies stored for that page along with the request. If a user is logged into a current session, the attacker could, for example, post a message on behalf of the logged in user without them noticing. The attacker never has to have access to the page’s cookies for this.



We can protect ourselves from this attack by using CSRF tokens. The concept is that when the browser gets a page from the server, it sends a randomly generated string as CSRF token as a cookie. Later, when your page performs a POST request it will send the CSRF token as a cookie and also in another way such as a parameter in the body or via an HTTP header like X-CSRF-Token .

An attacker will not be able to reproduce the same behavior with their hidden form since they won’t be able to access the cookie to retrieve the value and send it along with their malicious POST request.

This concept can be implemented in pretty much any web application but let’s look at how we can implement it in an Express application.

Getting the board ready

First we need an application to see how the CSRF vulnerability works in reality and how we can protect ourselves from it. If you already have an existing Express application, feel free to perform the following steps on it. Alternatively follow the next steps to set up our demo application.

Before we get started make sure you have Node.js and npm or another package manager installed. Start the new project by running the following commands in your terminal: