Synchronizer Token Pattern
I Discussed Cross-Site Request Forgery and about the Double Submit Cookie Pattern in the previous blog. Refer to this blog, if you want more information about CSRF and Double Submit Cookie Pattern
in this blog, I am going to discuss the Synchronizer Token Pattern
What is Synchronizer token pattern?
Synchronizer token pattern (STP) is a technique where a token, secret and unique value for each request, is embedded by the web application in all HTML forms and verified on the server side. SPT is using to preventing CSRF attacks from the attackers. Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data since the attacker has no way to see the response to the forged request.
Let’s understand Synchronizer token pattern with a flow diagram,
- User sends GET request to a server
- Server sets the cookie with session_id, and saving session data with the token
- Server returns HTML with a form containing token in a hidden field.
- User submits form, along with a hidden field.
- Server compares token from the submitted form (hidden field) with the token saved in the session storage. If they match, it means that form is submitted by a user.
Implementation
Let’s look a sample project,
This application is developed using PHP & JS. ( Github link — click here)
First, you need to login to the application by entering username and password. For the demo, I have hardcoded the credentials (username: kaviru, password:Kaviru98)
Upon successful login, a user can submit something including Account Number,Name and amount.
There is a function generate token, it will be a create a random number (it can be anything unique) and it will be saved in the session variable call token. that will be save in the server side. that token will generate for only that person who logged in.
After validating the credentials and if the user is authenticated, the user will be redirected to syncronizer_csrf_token.php where you can add a transaction details to the application.
To retrieve the CSRF token an AJAX call should be executed. The retrieved CSRF token will be stored in a hidden field in application from which is in syncronizer_csrf_token.php
The CSRF token will be validated by the function called validateToken () When a user adds account number, name and amount to the application, the request contains the generated CSRF token. Then the server validates session-id which is in the request header using the one that is stored in the server-side, and it compares the CSRF token in the body with the token in the request header.
Finally, if the POST request had the valid CSRF token then the server will return a success message.
Otherwise, it will show an error
Thank you. See you soon