What is Cross-Site Request Forgery (CSRF)?

Oswaldo Ferreira
Feb 25, 2017 · 2 min read

September 15, 2016

As we know, sessions are (normally) stored in cookies on our browser, and it’s lifecycle is based on the expiration logic of applications that stored it there.

Since we keep this data that identifies us while we continue using the pletora which is the web, we may suffer from an attack called “Cross-Site Request Forgery”. Imagine the following situation:

There are easy ways to protect your application from this “sleeping giant”, and some frameworks deal with this out of the box.

Use GET and POST appropriately.

Map your actions and resources mindfully, mutable actions cannot be accessible by GET method.

A security token in non-GET requests will protect your application from CSRF.

Correctly mapping your actions can’t be enough. There’s a simple code proving that:

<a href="http://www.harmless.com/" onclick=" var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = 'http://www.example.com/account/destroy'; f.submit(); return false;">To the harmless survey</a>

Security token verification rely on the following process:

Every non-GET request made to your server have to send a token which isn’t provided by anyone but your own server. When there’s a match, everything is fine and we’re good to proceed.

Rails deals with all this process with a simple one-liner on your controller:

protect_from_forgery with: :exception

Originally published at words.oswaldo.me.

Oswaldo Ferreira

Written by

Backend Engineer at http://GitLab.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade