Codeigniter Ajax Forbidden



我对这个禁忌问题感到非常困惑。首先,我检查了相关的stackoverflow帖子,并且谷歌搜索了足够的搜索,但仍然不知道。

项目详细信息:

- Currently used libraries:
    1. Carabiner (https://github.com/bcit-ci/CodeIgniter/wiki)
    2. Template (https://github.com/jenssegers/codeigniter-template-library)
    3. hmvc
    3. instagram_api 
- CSRF Protection turned on (I don't want false the protection)
- Followed main posts
    1. https://stackoverflow.com/questions/40225908/ajax-post-not-working-codeigniter
    2. https://stackoverflow.com/questions/22527412/403-forbidden-access-to-codeigniter-controller-from-ajax-request
- ISSUE: 403 Forbidden ("The action you have requested is not allowed.")

html

instagram.php

form_open()函数生成了隐藏的字段,用于访问令牌,并且包含在ajax发布数据中。

<input type="hidden" name="csrf_token_localhost" value="3f5887fd41ac4eaa9b558afa7cb4a6de">
...
<?php echo form_open('admin/getInstagramAccessToken', array('id' => 'instagram_settings', 'class' => 'form-horizontal row-border')); ?>
...
    <div class="col-sm-8 col-sm-offset-2">
        <?php  echo form_submit('submit', 'Get my access token', ['class' => 'btn-primary btn btn-get-token']); ?>
    </div>
...
<?php echo form_close(); ?>

javascript

adminscript.js

$('#instagram_settings').submit(function( event ) {
    var posting_data = $( this ).serializeArray();
    event.preventDefault();
    
    $.ajax({
        type: 'POST',
        dataType: 'json',
        async: true,
        cache: false,
        data: posting_data,
        url: 'admin/getInstagramAccessToken',
        success: function(json) {
            try{
                console.log(json);
            }catch(e) {
                console.log('Exception while request..');
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR, textStatus, errorThrown);
        },
        complete: function() {
            console.log('ajax complete');
        }
    })

控制器

admin.php

public function getInstagramAccessToken() 
{
    if ($this->input->is_ajax_request()) 
    {
        $response['status'] = 'success';
        echo json_encode($response);
    }
    else
    {
        // if the request if not ajax then show 404 error page
        show_404();
    }
    
}

当我使CSRF保护状态错误时,它们都可以正常工作。或者,当我从"帖子"更改帖子类型时要"获取"。方法。

两个图像的Dropbox链接:

  1. 隐藏的CSRF代币字段在形式加载之后

  2. 发布数据

https://www.dropbox.com/sh/e93ubgwzv9zir5j/aaa6vf5iwc1m7rtpgwgcpub4a?dl = 0

您可以通过使用AJAX请求发送CSRF令牌来传递此问题。之所以发生这种情况,是因为您将CSRF保护放在" ON"模式下。仅当您通过Get或明确将CSRF"关闭"发送请求时,才可以绕过这一点,这当然不建议您使用。

因此,解决方案是将CSRF令牌包括在您的Ajax请求中。

阅读这篇文章,以了解有关将CSRF令牌放在Ajax请求上的更多信息。

编辑:理想情况下,您通过AJAX请求中的数据选项发送CSRF令牌。检查此链接以获取更多信息

请在您的每个形式中添加此片段。

             <?php  $csrf = array(
            'name' => $this->security->get_csrf_token_name(),
            'hash' => $this->security->get_csrf_hash()
             ); ?>   
              <input type="hidden" name="<?php echo $csrf['name']; ?>" 
              value="<?php echo$csrf['hash']; ?>" />

最新更新