簡體   English   中英

403 禁止從 ajax 請求訪問 CodeIgniter 控制器

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

我在向 codeigniter 控制器發送 ajax 請求時遇到問題。 它正在返回 404 禁止訪問錯誤。 我發現了一些與此類似的問題,但我不確定它是否特定於 CodeIgniter 框架,並且該線程中給出的解決方案也沒有解決我的問題。 下面是我的ajax請求。 我想知道這可能是因為 CI Application 文件夾的根文件夾的 .htaccess ,但我還不想更改其默認配置。

向 CI 控制器發送 ajax 請求是實現此目的的正確方法嗎? 如果沒有,請提出任何建議。 謝謝!

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 使用csrf_protection ,您可以簡單地將它與 Ajax 和 JQuery 一起使用。 這個(最終?)解決方案適用於多個 Ajax 請求(沒有 403 ;-) 並保持安全性)。

更改配置

打開文件 /application/config/config.php 並將行 $config['csrf_token_name'] 更改為:

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

您可以使用其他名稱,但在以后的步驟中隨處更改。

在您的 Javascript 中添加 CSRF

在視圖中添加腳本; 對我來說是在 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>

此腳本創建一個名為CFG的對象。 此對象可用於您的 Javascript 代碼。 CFG.url 包含您網站的 url 和 CFG.token ...令牌。

自動更新CSRF

將此代碼添加到您的部分$(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}});
    });
});

此腳本初始化 CSRF 令牌並在每次發送請求 Ajax 時更新它。

在 PHP 中發送 CSRF

我創建了一個名為 Ajax 的新控制器。 在笨,用它的鏈接是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));

    }

}

send函數會自動添加 CSRF 並在對象中轉換數組。

最終結果

現在,您可以非常簡單地將 Ajax 與 JQuery 結合使用!

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

結果 :

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

當請求獲取數據時,CSRF 會自動更新到下一個 Ajax 請求。

等等!

ajax_processor刪除<code>application/controller ,例如,

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

如果您使用htaccessroutingurl中隱藏index.php ,請嘗試使用此 url,

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

我遇到了同樣的問題,但現在我已經解決了這個問題。

首先,我在 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>

之后,當我們通過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');
    }
});

我希望這段代碼能幫助你,因為這對我有用。

    // 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