Synchronizer Token Pattern
- Sankalpa H.T.S
- Oct 11, 2019
- 2 min read
Updated: Oct 13, 2019
In this post, let’s discuss using a synchronizer token pattern to prevent CSRF (Cross-site request forgery.). 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. Then the token is generated by the server with ensuring the uniqueness. Here server generates token per every session. In that case, the attacker is unable to place a correct token in their requests to authenticate them.
There are a lot of ways to do CSRF attacks. You can get a good idea about them here from Wikipedia. You can obtain a good knowledge of the CSRF attack at the owasp.org website. For a better understanding, you should have some preliminary knowledge of cookies and how they work. If not please get some knowledge by referring MDN site.
Let’s look at a sample project,
This application is developed using PHP & JS.( Github link - click here)
Create a user login. I have hardcoded user credentials for demonstration purposes.


Upon login, generate session identifier and set as a cookie in the browser.

At the same time, generate the CSRF token and store it on the server-side. Store it in memory. The CSRF token is mapped to the session identifier.

In the website, implement an endpoint that accepts HTTP POST requests and respond with the CSRF token. The endpoint receives the session cookie and based on the session identifier, returns the CSRF token value.
Implement a webpage that has an HTML form. The method is POST and action is another URL on the website. When this page loads, execute the Ajax call via a javascript, which invokes the endpoint for obtaining the CSRF token created for the session.


Once the page is loaded, modify the HTML form’s document object model (DOM) and add a new hidden field that has the value of the received CSRF token.


Once the HTML form is submitted to the action, on the server-side, extract the received CSRF token value and check if it is the correct token issued for the particular session. I need to obtain the session cookie and get the corresponding CSRF token for the session and compare that with the received token value.

If the received CSRF token is valid, I will show a success message. If not show an error message.



The source link of the sample project:
Conclusion
The Synchronizer token pattern techniques described in this scenario are viable and worth a thought for any application that contains useful data.
Comments