AJAX + CSRF Protection in Codeigniter ?

Codeigniter 2.0 adds an important security feature to prevent CSRF (Cross Site Request Forgery) attacks. Even better, the feature is automatically added to your forms(if you enable CSRF in Config, and if you use CI form Helper).

You might like this post –
How to Enable CSRF (Cross Site Request Forgery) in CodeIgniter

How CSRF Protection Work in CodeIgniter?

if you visit page after enabling CSRF Protection, the CI form helper adds a hidden input element to the from with randomly generated hash String as a value (input field default name is csrf_test_name, you can change it in config file) and at the same time CI sets a cookie with same hash(the default Cookie name is csrf_cookie_name, as usual, you can change it in config). When the form is submitted by the user that hidden input is compared with the cookie value. If they do not match the request is rejected before it ever reaches your controller method(action).

This way you can protect your website from outside form submissions from the malicious users.

if you are not using CI’s form helper , hidden input field will not generate automatically you have to set it manually as shown below, past this in side your form.

Why my AJAX functions were returning 500 Internal Server Errors With CSRF

Because your CSRF validation is field, in order to fix this problem you have to pass your CSRF hidden input value with in your ajax request.

you can get hash value and pass it with JQuery something like this:

What if your numerous places to add ?

For this i am gonna use $.ajaxSetup . All post data from Ajax functions throughout your application will be merged with the data set by $.ajaxSetup.

Here is the Example :

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status