ci ajax js,javascript - Codeigniter ajax CSRF problem - Stack Overflow

本文介绍了解决CodeIgniter中CSRF令牌仅适用于单次请求的问题。通过在控制器中生成新的CSRF令牌,并将其与JSON响应一起返回,确保在后续的AJAX POST请求中能使用正确的令牌。在客户端JavaScript中,接收到新令牌后保存并用于下次POST请求,以增强安全性。
摘要由CSDN通过智能技术生成

The only problem with a few of the above answers is that a csrf token is only valid for one request, so if you make a post request via ajax and do not refresh the page you will not have the current csrf token for your next ajax post request. This is my solution:

In your CodeIgniter Controller:

$data = array('data'=> 'data to send back to browser');

$csrf = $this->security->get_csrf_hash();

$this->output

->set_content_type('application/json')

->set_output(json_encode(array('data' => $data, 'csrf' => $csrf)));

$data = the data to return to the browser

$csrf = new csrf token to be used by the browser for next ajax post request

Obviously you can output this in other ways but JSON is used mostly with ajax calls. Also include this token in every post response to be used for the next post request

Then in your next ajax request (javascript):

var token = data.csrf;

$.ajax({

url: '/next/ajax/request/url',

type: 'POST',

data: { new_data: 'new data to send via post', csrf_token:token },

cache: false,

success: function(data, textStatus, jqXHR) {

// Get new csrf token for next ajax post

var new_csrf_token = data.csrf

//Do something with data returned from post request

},

error: function(jqXHR, textStatus, errorThrown) {

// Handle errors here

console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );

}

});

Also remember that where I've got csrf_token:token replace crf_token with the name of your token found in application/config/config.php on line that states $config['csrf_token_name'] = 'csrf_token';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值