Cross Site Request Forgery

Learn about CSRF and how to protect against it.

Cross-Site Request Forgery (CSRF) is the opposite of an XSS exploit. Where XSS takes advantage of the user by means of a trusted web site, CSRF takes advantage of the web site by means of a trusted user.

Imagine an attacker who sends out fake emails with a link to delete a blog post or email. The target user clicks the link and arrives at a delete page. Because the user is an administrator with a valid session, your application goes ahead and deletes the record as requested. The link is a mystery to the user but now their account has been deleted without their consent. Not cool.

This doesn’t have to be a text link; it is often attached to an image or a button. It may sound like a small risk since most critical web site functions are behind forms that expect POSTed data. But this can just as easily be expanded upon to use a button or JavaScript to submit hidden forms.

How to protect against it

First, ensure GET requests do not perform data-altering actions. Anything that performs an action on data should require a POST, PUT, or DELETE request. If the user clicks a delete button, take them to a form used to confirm the action. If data-altering actions need to be performed over GET (maybe for a RESTful API), require a unique token in the query string. In the following examples, we use POST data, but the same concepts apply when dealing with GET requests. Set the token in the query string instead of the POST parameters.

Now that we are submitting forms for our data manipulations, we need to add CSRF tokens to our forms. Our CSRF tokens are a standard Nonce (Number used Once). Generate a random token, store it in the user’s session, and then add it as a hidden field to our form. Once the form is POSTed, we can check the CSRF token against the one in the session to validate the request.

First, create a function to generate the token. Node.js has a built-in crypto module that generates a random string that we can use as our CSRF token. Let’s use the randomBytes method and see how it works.

Get hands-on with 1200+ tech skills courses.