Preventing Cross-Site Request Forgery (CSRF) using Synchronizer Token Pattern

Dasuni Anupama
3 min readSep 18, 2018

With the development of the technology, as per today, data is stored in cloud and transactions are done online. It is crucial to make sure about the security of the data and transactions since hacking/attacking has already taken place. Cross Site Request Forgery is such a vulnerability in the websites, which targets state changing operations such as fund transferring, unfriend a friend from Facebook etc.

How Cross Site Request Forgery works ?

When a user login to bank, the bank website will create a session and once the user is authenticated, a session ID will set as a cookie in the browser. Only the user can see these cookies. Any other websites user visits, cant access these cookies and bank website can’t access other cookies of the user as well.

But there can be malicious websites, where it will motivate the user to perform some action like click a button, which contains a script to trigger a web call to the bank. Since the request is sent from bank’s domain, web browser will add the cookies to the request and send. Bank will authenticate it as the user, himself has requested and perform the requested action. In this case as in above diagram, requested action is fund transfer.

This is one of the most common example of CSRF attack where an undesired action is performed on behalf of the user making him a victim. Attacker gets all the privileges on behalf of the user.

Ways to Prevent :

There are two types of patterns to prevent this attack.

  1. Synchronizer Token Pattern
  2. Double Submit Cookie Pattern

In this blog let’s discuss how the Synchronizer Token Pattern prevents CSRF and how can we implement it in a Java application.

Synchronizer Token Pattern

In Synchronizer Token pattern, the application generate a CSRF token which can use only one time and store it server side against the sessionID. This token will be sent embedded to the HTML. When the user requests an action, this token will be sent along with other parameters. The server will validate the sessionID and this token value. If they match, the request will be completed.

The token is generated uniquely per form. Therefore, the attacker has no way of accessing this. Even if the attacker submits the other parameters, since the token is unavailable, the server will not complete the action. Thereby, CSRF is prevented.

Sample Application

Implementation of Login page:-

Implementation of Simple Storage class:-

Implementation of Validator class:-

Confirmation Page:-

Home Page:-

Full Implementation of this application can be found here.

--

--

Dasuni Anupama

Software Engineer | Graduate @ SLIIT 🎓| Cloud Computing Enthusiast | Web Dev Enthusiast