CSRF token and how it works

Thanh Tri
3 min readJul 11, 2022

In this article, I will discuss about how CSRF token protect the web application from CSRF attack

Photo by Franck on Unsplash

What is CSRF attack ?

Cross-site Request Forgery (CSRF) attack is an attack that forces an end user to submit unwanted request on a Web application in which they are currently authenticated. This attack exploits a vulnerability that if web application cannot differentiate between a request generated by an enduser and a request generated by a user without their consent.

Let’s take this scenario to understand more about CSRF attack:

1. Assume you are currently logging into banking website at www.bank.com

2. To make a money transfer at www.bank.com, we make a request :

POST http://bank.com/transfer?accountNo=1234&amount=100

3. You visit www.play-boy.com, not knowing that this is a malicious site and you are still logged in www.bank.com due to session in cookie.

4. If the owner of www.play-boy.com knows the form request (easy) and guesses you are logged in www.bank.com (lucky), they could include this hidden request under a button:

POST http://bank.com/transfer?accountNo=6789&amount=500Note: 6789 is the account number of the owner of malicious site

5. You accidentally click that button and www.bank.com cannot recognize the origin of the request so it sends the request along with your credentials in session in cookie. BOOOOM , your money is gone !

What is CSRF token ?

So to protect the web application from CSRF attack, one of the solutions is using CSRF token to validate.

CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client, then the client attaches it into the subsequent request. When the later request is made, the server-side application validates that the request includes the expected token and rejects if the token is missing or invalid.

Below is the work flow of how CSRF token works:

When a CSRF token is generated, it will be stored in a user’s session. Also, the client-side will request to get the CSRF token from the server-side so only the client-side of user has this token and then attaches this token in every subsequent requests sending to server side.

When a request is sent to the server-side, the server-side will get the CSRF token from the request and compares it with the CSRF token in the user’s session. Obviously, the malicious site doesn’t have anyway to get that CSRF token so it will always get failed response when attempting to send request from their domain. This is how CSRF token prevents CSRF attack.

Reference

https://portswigger.net/web-security/csrf/tokens#:~:text=When%20a%20CSRF%20token%20is,stored%20in%20the%20user's%20session.

--

--