Cross-Site Request Forgery is a way of making malicious requests to web endpoints. This should be prevented in order to protect a website's user privacy and confidentiality. This blog post demonstrated 2 ways of preventing CSRF using vanilla PHP.
Method 1 : Synchronizer Token
Method 2 : Double submission Cookies.
This demonstration has 3 files in it.
1. index.php -> contains the login form and the validation code for the login. At the point of login, it creates a CSRF token saves in the server side.
2. protected.php -> contains the are protected by the login, which is a contact form.
3. get-token.php -> This file is the endpoint that gives the Token to the AJAX request.
Synchronizer Token Method
when a POST request is made to the server it should contain a CSRF token previously fetched by an AJAX request. At the point of validation, serer side cide compares this token with the token stored in the session memory. If it matches, it'll be safe to process the data. This way prevents malicious CSRF attacks. Here's how the login form looks like in the begining.
After the login it looks like this.
After the protected area page loads, the JS code fetches the token from server side and adds it to the form on the fly. Shown below is the dynamically added token field vs the initial source code.

When the form submits, it checks for the token and if it does not match it produces an error. As an additional step, i have added a feature to dynamically generate the token at the server side. The token is made from sha1(session ID + server secret + session start time). Out of those, only the session ID is sent to the client side. So each time it validates in the server side it generated the token again and compares it with the token from client side.
Double Submission Cookie method
This method is a little different from the previous one. Instead of saving the CSRF token on server side, it sets a cookie with the token in it. After the page loads, th e JS code fetches it from the cookie and places it in the form. The rest of the process stays the same.
Wednesday, May 30, 2018
Preventing Cross Site Request Forgery with PHP
8:02 PM
No comments
Subscribe to:
Post Comments (Atom)






0 comments:
Post a Comment