简体   繁体   中英

Codeigniter not accepting jQuery POST with CSRF protection enabled

I've been trying to POST to a Codeigniter controller (while CSRF protection is enabled) but this keeps failing with HTTP/1.1 500 Internal Server Error and This action is not allowed page.

I tried sending the csrf token along with POST data using the following method (which I found here ) but it does not seem to work.

<script type="text/javascript" src="js/libs/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/libs/jquery.cookie.js"></script> 
<div id="display">Loading...</div>
<script type="text/javascript">
   // this bit needs to be loaded on every page where an ajax POST may happen
   $.ajaxSetup({
       data: {
           csrf_token: $.cookie('csrf_cookie')
        }
    });

   // now you can use plain old POST requests like always
   $.post('http://localhost/index.php/handler/test', { name : 'Grim'}, function(data){ $('#display').html(JSON.stringify(data)); });

Here's my Codeigniter config.php file:

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_token';
$config['csrf_cookie_name'] = 'csrf_cookie';
$config['csrf_expire'] = 1800;

Here's the controller:

function test()
{

    echo json_encode($_POST);
}

add csrf token to data before posting

$.ajax({
            type: "POST",
            url: url,
            data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',/*----your data-----*/}

        })

csrf token needs to be send along every request so it needs to be specified by the above echo statements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM