javascript Codeigniter (CSRF) jQuery ajax 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7351849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:49:46  来源:igfitidea点击:

Codeigniter (CSRF) jQuery ajax problem

phpjavascriptjqueryajaxcodeigniter

提问by Dexty

I've got a issue here, i keep getting a error when i try to post something with ajax (POST). I know it is the CSRF that gives me these problems and I've been tried back and forth trying to find a solution. However, i hope somebody here can help me out!

我在这里遇到了一个问题,当我尝试使用 ajax (POST) 发布内容时,我不断收到错误消息。我知道是 CSRF 给了我这些问题,我已经反复尝试寻找解决方案。但是,我希望这里有人可以帮助我!

This is the error i keep getting (from google chrome inspector),

这是我不断收到的错误(来自谷歌浏览器检查员),

*Failed to load resource: the server responded with a status of 500 (Internal Server Error) XHR finished loading: "http://localhost/woho/ajax/images".*

*无法加载资源:服务器响应状态为 500(内部服务器错误) XHR 已完成加载:“http://localhost/woho/ajax/images”。*

PHP (Controller)

PHP(控制器)

class Ajax extends CI_Controller {

    function images() {

        echo 'Hello World';

    }

}

Javascript

Javascript

var ID = $(".imageWrap:last").attr("id");
var baseurl = "http://localhost/woho/";
var doScroll = 1;
var cct = $.cookie('csrf_cookie_name');

if (location.href == baseurl) {
    $(window).scroll(function(){
        if ($(window).scrollTop() > $('body').height() / 2) {
            if(doScroll == 1) {                   
                $.post(baseurl + 'ajax/images',{'id' : ID, 'csrf_token_name': cct}, function(data) {
                    alert(data);
                    $("#wrapper_content").append(data);
                    ID++;
                });
            }
        }
    });
}

my CCT var from javascript gives me the correct token or "hash" but when the javascript sends the ajax request codeigniter returns an error like,

我的来自 javascript 的 CCT var 给了我正确的令牌或“哈希”,但是当 javascript 发送 ajax 请求时,codeigniter 返回一个错误,例如,

An Error Was Encountered The action you have requested is not allowed.

遇到错误 不允许您请求的操作。

How can i fix this? do i need to validate the CSRF Token or something in my controller?

我怎样才能解决这个问题?我是否需要验证 CSRF 令牌或控制器中的某些内容?

I'm using Codeigniter 2.0.3

我正在使用 Codeigniter 2.0.3

回答by Alfonso Rubalcava

Try (javascript):

尝试(javascript):

var ID = $(".imageWrap:last").attr("id");
var baseurl = "http://localhost/woho/";
var doScroll = 1;
var cct = $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");

if (location.href == baseurl) {
    $(window).scroll(function(){
        if ($(window).scrollTop() > $('body').height() / 2) {
            if(doScroll == 1) {                   
                $.post(baseurl + 'ajax/images',{'id':ID,'<?php echo $this->security->get_csrf_token_name(); ?>': cct}, function(data) {
                    alert(data);
                    $("#wrapper_content").append(data);
                    ID++;
                });
            }
        }
    });
}

回答by joni jones

check value of your $config['csrf_token_name']in /application/config/config.php as default is setted as csrf_test_namenot csrf_token_name.

检查您$config['csrf_token_name']在 /application/config/config.php 中的默认值设置为csrf_test_name而不是csrf_token_name

This decision if you not want to use PHP code in Javascript.

这个决定如果你不想在 Javascript 中使用 PHP 代码。

$.ajax({
    url: 'some_url',
    type: 'POST',
    data: {csrf_test_name: $.cookie('csrf_cookie_name')}
});

This code works fine.

这段代码工作正常。

回答by Reza-S4

If you use the form_open("/some",'id="some_form"')and form_close(), CI create a hidden input that keep the csrf_token_name and it value.

如果使用form_open("/some",'id="some_form"')and form_close(),CI 创建一个隐藏的输入,保留 csrf_token_name 和它的值。

so , in your AJAX request , you can get the form by serialize it and send form !

因此,在您的 AJAX 请求中,您可以通过序列化并发送表单来获取表单!

For example:

例如:

<script>
var _form = $("#some_form").serializeArray();
$.ajax({
    data: _form,
    type: 'post',
    url: '<?php echo base_url();?>some',
    async: true,
    success: function(output){
        alert(output);
    },
    complete: function(output){},
    fail: function(err){}
});
</script>

The CSRF always was my problem and by this method, it solved!!

CSRF 一直是我的问题,通过这种方法,它解决了!!

回答by avinashizhere

it may be late but i found this perfect solution sort of hack but should work

可能已经晚了,但我发现这个完美的解决方案有点像黑客,但应该有效

if (isset($_SERVER["REQUEST_URI"])) 
{
    if(stripos($_SERVER["REQUEST_URI"],'/mypage') === FALSE)
    {
        $config['csrf_protection'] = TRUE;
    }
    else
    {
        $config['csrf_protection'] = FALSE;
    } 
} 
else 
{
    $config['csrf_protection'] = TRUE;
} 

// in config.php file ci 2.*

// 在 config.php 文件中 ci 2.*

found solution from this post

这篇文章中找到了解决方案

回答by Sumit Kumar Gupta

I was facing same problem but now I have fixed this problem.

我遇到了同样的问题,但现在我已经解决了这个问题。

First of all, I have created csrf_token in header.php for every pages like below code

首先,我在 header.php 中为每个页面创建了 csrf_token,如下面的代码

$csrf = array(
                'name' => $this->security->get_csrf_token_name(),
                'hash' => $this->security->get_csrf_hash()
        );

<script type="text/javascript">
    var cct = "<?php echo $csrf ['hash']; ?>";
  </script>

After that, when we are sending particular value through ajax then we will have to sent csrf token like below code

之后,当我们通过ajax发送特定值时,我们将不得不发送如下代码的csrf令牌

$.ajax({
    url:"<?php echo APPPATHS.'staff_leave/leaveapproval/getAppliedLeaveDetails'; ?>",
    data:{id:id,status:status,'<?php echo $this->security->get_csrf_token_name(); ?>': cct},
    method:"post",
    dataType:"json",
    success:function(response)
    {
        alert('success');
    }
});

I hope this code will help you because this is working for me.

我希望这段代码能帮助你,因为这对我有用。

回答by Mir Zak

Just follow this code:

只需按照以下代码:

$.ajax({
    type : 'post',
    url  : 'Your URL',
    data : {
        id: id,
        '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
    },
    datatype: 'json',
    success : function(data){}
});