Synchronizer Token Pattern to prevent Cross-Site Request Forgery (CSRF)
Cross-Site Request Forgery known as CSRF attack that tricks a web browser into executing an unwanted action in an application to which a user is logged in.
An effective CSRF attack can be obliterating for both the business and client. It can bring about harmed customer connections, unapproved fund exchanges, changed passwords and information burglary—including stolen session cookies.
Synchronizer Token Pattern is an one method which is used to prevent this attack. below image explain how Synchronizer Token Pattern works.

source : insidethecpu.com
In this blog post I am demonstrating a sample project, how to implement Synchronizer Token Pattern.
1. You need to have a web server to launch this project.
(Download wamp server from here -> http://www.wampserver.com/en/ and install it and run it.)
2. First create a login page to authenticate user. I created login.html page which authenticates users using java script. Since this is a demonstration,I used hard-coded credentials.
This is the login.html page and user authenticating java script function.

user_validation.js
3. When a successful login occurred login.html page invoke CSRF_Token_Generator.php page to generate CSRF token for current user session.
CSRF_Token_Generator.php
This page generate CSRF token and store it as text file under local directory called “tokens”. text file is named with session id so then it can map when we want to validate CSRF token later.
4. After this process it redirect to Home.php page where user enter his details in simple form for submission.
Home.php
5. When this page load it invoke java script which execute ajax call to get CSRF token form server. In that process ajax request send current session id and server respond to the request with matching CSRF token. Then token is set in hidden field inside the Home.php
token_request.js
In this function it is calling Token_Issuer.php page to get correct CSRF token.
Token_Issuer.php
This page returns the matching CSRF token to given session.
6. Next user enter his details and submit the data. During the submission process home.php page redirect to Token_Validation.php page where server check whether this data comes from valid user. To do that server compare the token value in the hidden filed with original token value stores in server.
Token_Validation.php
7. According to the token comparison results it shows proper message in Data_Receiving_End_Point.php page
You can download all source codes of this project from the following link.
Author :- G M H Wijeratne
Comments
Post a Comment