简体   繁体   English

403 禁止从 ajax 请求访问 CodeIgniter 控制器

[英]403 Forbidden Access to CodeIgniter controller from ajax request

Im having trouble with sending an ajax request to codeigniter controller.我在向 codeigniter 控制器发送 ajax 请求时遇到问题。 It is throwing back a 404 Forbidden Access error.它正在返回 404 禁止访问错误。 I have found some sort of similar question to this but im not sure if its particular to CodeIgniter framework, and also the solution give in that thread did not solve my problem.我发现了一些与此类似的问题,但我不确定它是否特定于 CodeIgniter 框架,并且该线程中给出的解决方案也没有解决我的问题。 below is my ajax request.下面是我的ajax请求。 Im wondering this is probably because of the .htaccess of the root folder of CI Application folder, but i dont want to change its default configuration yet.我想知道这可能是因为 CI Application 文件夹的根文件夹的 .htaccess ,但我还不想更改其默认配置。

Is sending ajax request to CI controller the correct way of implementing this?向 CI 控制器发送 ajax 请求是实现此目的的正确方法吗? if not, any suggestion please.如果没有,请提出任何建议。 Thanks!谢谢!

var ajax_load = '{loading gif img html}';
var ajax_processor = 'http://localhost/patientcare-v1/application/controller/ajax_processor/save_physical_info';

$("#save").click(function(){
    $("#dialog-form").html(ajax_load);
    $.post(
        ajax_processor,
        $("#physical-info").serialize(),
        function(responseText){
            $("#dialog-form").html(responseText);
        },
        "json"
    );
});

CodeIgniter use csrf_protection , you can use it with Ajax and JQuery simply. CodeIgniter 使用csrf_protection ,您可以简单地将它与 Ajax 和 JQuery 一起使用。 This (ultimate ?) solution work on multiple Ajax request (no 403 ;-) and preserve the security).这个(最终?)解决方案适用于多个 Ajax 请求(没有 403 ;-) 并保持安全性)。

Change the configuration更改配置

Open the file /application/config/config.php and change the line $config['csrf_token_name'] by :打开文件 /application/config/config.php 并将行 $config['csrf_token_name'] 更改为:

$config['csrf_token_name'] = 'token';

You can use another name, but change it everywhere in future steps.您可以使用其他名称,但在以后的步骤中随处更改。

Add CSRF in your Javascript在您的 Javascript 中添加 CSRF

Add script in a view;在视图中添加脚本; for me is in footer.php to display the code in all views.对我来说是在 footer.php 中以在所有视图中显示代码。

<script type="text/javascript">
    var CFG = {
        url: '<?php echo $this->config->item('base_url');?>',
        token: '<?php echo $this->security->get_csrf_hash();?>'
    };
</script>

This script create an object named CFG .此脚本创建一个名为CFG的对象。 This object can be used in your Javascript code.此对象可用于您的 Javascript 代码。 CFG.url contain the url of your website and CFG.token ... the token. CFG.url 包含您网站的 url 和 CFG.token ...令牌。

Automatically renew the CSRF自动更新CSRF

Add this code in your part $(document).ready(function($){---}) as将此代码添加到您的部分$(document).ready(function($){---})作为

$(document).ready(function($){
    $.ajaxSetup({data: {token: CFG.token}});
    $(document).ajaxSuccess(function(e,x) {
        var result = $.parseJSON(x.responseText);
        $('input:hidden[name="token"]').val(result.token);
        $.ajaxSetup({data: {token: result.token}});
    });
});

This script initialize the CSRF token and update it everytime when a request Ajax is sended.此脚本初始化 CSRF 令牌并在每次发送请求 Ajax 时更新它。

Send the CSRF in PHP在 PHP 中发送 CSRF

I've created a new controller, named Ajax.我创建了一个名为 Ajax 的新控制器。 In CodeIgniter, the link to use it is http://www.domain.ltd/ ajax/foo在笨,用它的链接是http://www.domain.ltd/ AJAX /富

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Ajax extends CI_Controller {

    public function foo() {
        $this->send(array('foo' => 'bar'));
    }

    private function send($array) {

        if (!is_array($array)) return false;

        $send = array('token' => $this->security->get_csrf_hash()) + $array;

        if (!headers_sent()) {
            header('Cache-Control: no-cache, must-revalidate');
            header('Expires: ' . date('r'));
            header('Content-type: application/json');
        }

        exit(json_encode($send, JSON_FORCE_OBJECT));

    }

}

The send function add the CSRF automatically and transform an array in object. send函数会自动添加 CSRF 并在对象中转换数组。

The final result最终结果

Now, you can use Ajax with JQuery very simply !现在,您可以非常简单地将 Ajax 与 JQuery 结合使用!

$.post(CFG.url + 'ajax/foo/', function(data) {
    console.log(data)
}, 'json');

Result :结果 :

{"token":"8f65cf8e54ae8b71f4dc1f996ed4dc59","foo":"bar"}

When the request get data, the CSRF is automatically updated to the next Ajax request.当请求获取数据时,CSRF 会自动更新到下一个 Ajax 请求。

Et voilà !等等!

Remove the <code> and application/controller from your ajax_processor like,ajax_processor删除<code>application/controller ,例如,

var ajax_processor = 'http://localhost/patientcare-v1/index.php/ajax_porcessor/save_physical_info';

If you are hiding index.php from url by using htaccess or routing then try this url,如果您使用htaccessroutingurl中隐藏index.php ,请尝试使用此 url,

var ajax_processor = 'http://localhost/patientcare-v1/ajax_porcessor/save_physical_info';

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.我希望这段代码能帮助你,因为这对我有用。

    // Select URIs can be whitelisted from csrf protection (for example API 
    // endpoints expecting externally POSTed content). 
    // You can add these URIs by editing the 
    // ‘csrf_exclude_uris’ config parameter:
    
    // config.php
    // Below setting will fix 403 forbidden issue permanently
    
    $config['csrf_exclude_uris'] = array(
        'admin/users/view/fetch_user', // use ajax URL here
    );

$('#zero-config').DataTable({
            
                "processing" : true,
                "serverSide" : true,             
                "order" : [],
                "searching" : true,
                "ordering": false,
                "ajax" : {
                    url:"<?php echo site_url(); ?>admin/users/view/fetch_user",
                    type:"POST",
                    data: {                        
                    },
                },
                
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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