Cross-site request forgery (CSRF) is an attack that exploits the fact that a user is logged in to a site to make a malicious request to that website with the user's browser. For example, the user can be tricked into visiting a page that's making a background request to another website for which the user is authenticated.
Let's create a simple Express application that allows users to place orders. Since we're just trying to showcase how to be protected against CSRF attacks, we won't have a login system; just suppose that it's a single-user application this time. All the orders will be stored into memory.
This application will have two pages: the home page that allows the user to place an order, and the orders page that lists all the orders made by the user. Besides the two pages mentioned, there is another Express route to place an order.
Along with express
, we will also need to install the body-parser
and ejs
modules for this example. The server.js
file...