I am turning CSRF security on in my code:
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
Now, I am adding a hidden field in my form:
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
In my form post, I am getting the data:
csrf_test_name:50711c69fc79244945f0aaecf7ac1aa4
teacher_name:
teacher_mobile:
teacher_email:
teacher_about:
But, still I am getting errors like:
<h1>An Error Was Encountered</h1>
<p>The action you have requested is not allowed.</p> </div>
I am sending data using ajax call:
submitHandler: function (form) {
var URL = $("#teacherForm").attr("action");
var METHOD = $("#teacherForm").attr("method");
$.ajax({
type: METHOD,
url: URL,
data: $(form).serialize(),
success: function (data) {
var data = $.parseJSON(data);
......
......
What am I doing wrong?
I suggest you change one CSRF config setting:
$config['csrf_regenerate'] = FALSE;
and see if that helps.
If you want to regenerate the hash on each POST and use AJAX you will need to return the new hash to the browser and update the CSRF hidden field values so the next POST will pass the security check.
You would be wise to use the Form Helper instead of manually creating the hidden CSRF input. In a view that would look like
echo form_open('controller/method');
Documentation on form_open() here.
Read about how using form_open() add the hidden CSRF here.
Once try to add csrf in ajax request not in form.Its worked for me
Here is the code :
submitHandler: function (form) {
var URL = $("#teacherForm").attr("action");
var METHOD = $("#teacherForm").attr("method");
var data= $(form).serialize();
var post_data = {
'result': data,
'<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
};
$.ajax({
type: METHOD,
url: URL,
data:post_data,
success: function (data) {
var data = $.parseJSON(data);
......
......