【问题标题】:How to make Ajax work when csrf_regeneration is true in CodeIgniter3?当 CodeIgniter 3 中的 csrf 再生为真时,如何使 Ajax 工作?
【发布时间】:2015-07-06 08:45:45
【问题描述】:

我目前正在 CI3 上开展我的项目,但我在 CSRF_Regeneration 上遇到了一些问题。

我的目的:

我将在用户登录和注册时使用 CSRF 来保护我的表单数据,方法是在用户输入电子邮件时检查电子邮件是否存在。

如果 CSRF_generation 为 False 则有效

当我将 CSRF_Regeneration 配置为 False 并且 csrf_expire 将在 7200 时过期。

问题当我将CSRF_generation设为TRUE时会出现如下问题

POST http://localhost/com/account/register 403 (Forbidden)

这是检查电子邮件是否存在的 Ajax

<script type="text/javascript">
    $(document).ready(function () {

        $("#email-error").css({'display': 'none', 'color': 'red'});
        $("#email").keyup(function () {
            var emailValue = $("#email"); // This is a bit naughty BUT you should always define the DOM element as a var so it only looks it up once
            var tokenValue = $("input[name='csrf_token_name']");
//            console.log('The Email length is ' + emailValue.val().length);
            if (emailValue.val().length >= 0 || emailValue.val() !== '') {
//                console.log('Token is ' + tokenValue.val()); // Now why is this not getting the coorect value?? It should
                $.ajax({
                    type: "post",
                    url: "<?php echo base_url('account/check_user_existing'); ?>",
                    data: {
                        '<?php echo $this->security->get_csrf_token_name(); ?>': tokenValue.val(),
                        email: $("#email").val()
                    },
                    dataType: "json",
                    cache: false,
                    success: function (data) {
//                        console.log('The returned DATA is ' + JSON.stringify(data));
//                        console.log('The returned token is ' + data.token);
                        tokenValue.val(data.token);
                        if (data.response == false) {
                            $("#email-error").css({'display': 'none'});
                            $(".form-error").css({'border': '', 'background-color': '', 'color': ''});
                            document.getElementById("csubmit").disabled = false;
                        } else {
                            $("#email-error").css({'display': 'inline', 'font-size': '12px'});
                            $(".form-error").css({'border': '1px solid red', 'background-color': 'rgba(255, 0, 0, 0.17)', 'color': 'black'});
                            document.getElementById("csubmit").disabled = true;
                        }
                    }
                });
            }
        });
    });
</script>

这里是我的表格

<?PHP echo form_open('account', array('method' => 'POST', 'id' =>'createform')); ?>
 <div class="control-group">
   <label class="control-label"  for="lname">Last Name</label>
   <div class="control">
    <?PHP echo form_input('lastname', set_value('lastname', ''), 'id="lastname" class="form-control ln-error" ') ?>
    </div>
   </div>
 <div class="control-group">
   <label class="control-label"  for="fname">First Name</label>
     <div class="control">
    <?PHP echo form_input('firstname', set_value('firstname', ''), 'id="firstname" class="form-control ln-error" ') ?>
     </div>
   </div>
  <div class="control-group">
  <label class="control-label"  for="email"> Email <span id="email-error">Email is existed</span></label>
   <div class="control">
     <?PHP echo form_input('email', set_value('email', ''), 'id="email" class="form-control ln-error" placeholder="Example@website.com" ') ?>
      </div>
     </div>
  <div class="control-group">
      <label class="control-label" >Password</label>
       <div class="control">
       <?PHP echo form_password('pass', set_value('pass', ''), 'id="pass" class="form-control ln-error" ') ?>
      </div>
     </div>
  <div class="control-group">
     <div class="controls">
       <?PHP echo form_submit('csubmit', "Create Account", 'id="csubmit" class="btn btn-success btn-lg" ') ?>
       </div>
      </div>
<?PHP echo form_close(); ?>

这是控制器检查用户的方法

public function check_user_existing() {

        $data = $this->input->post('email'); // This should be passed in as a parameter as depending upon Form Names isn't that good.
        $new_token = $this->security->get_csrf_hash();
        $response = FALSE; // Set the default so we know what it is in case the IF fails or we could use an else at the end but this is nicer.
        $check_email = $this->user->check_user_exist_email($data);
        if ($check_email == TRUE) {
            $response = TRUE; // Change it to TRUE if it's true but our $response Always has a KNOWN Value :)
        }
        echo json_encode(array('response' => $response, 'token' => $new_token));
        exit(); // This is here for safety... Terminate and leave!
    }

感谢您的建议

【问题讨论】:

  • 你在表单上做了什么导致它失败?
  • @TimBrownlaw 我爸爸昨天做 CSRF_regeneration 的时候是 False 我忘了把它设置为 True 之后当我把它设置为 true 时发生了错误

标签: ajax codeigniter


【解决方案1】:

我遇到了这个问题,我不想csrf_regeneration 设置为 FALSE,因为它不太安全。

所以我做了以下事情:

csrf_token_name = '<?php echo $this->security->get_csrf_token_name(); ?>';
csrf_cookie_name = '<?php echo $this->config->item('csrf_cookie_name'); ?>';
$(function ($) {
    // this bit needs to be loaded on every page where an ajax POST 
    var object = {};
    object[csrf_token_name] = $.cookie(csrf_cookie_name);
    $.ajaxSetup({
        data: object
    });
    $(document).ajaxComplete(function () {
        object[csrf_token_name] = $.cookie(csrf_cookie_name);
        $.ajaxSetup({
            data: object
        });
    });
});

如果您使用的是 blueimp/jQuery-File-Upload,您可以执行以下操作:

$('#fileupload').bind('fileuploadsubmit', function (e, data) {
    data.formData = [
        {name: csrf_token_name, value: $.cookie(csrf_cookie_name)}
    ]
});

参考文献:

  1. https://www.codeigniter.com/user_guide/libraries/security.html
  2. http://jerel.co/blog/2012/03/a-simple-solution-to-codeigniter-csrf-protection-and-ajax
  3. http://api.jquery.com/ajaxcomplete/
  4. https://api.jquery.com/jquery.ajaxsetup/
  5. https://github.com/blueimp/jQuery-File-Upload/wiki/How-to-submit-additional-form-data#setting-formdata-on-upload-start

【讨论】:

  • 我整个上午都在研究这个问题,我有很多关于这个问题的帖子。您的建议对我来说按预期工作。非常感谢!!!
【解决方案2】:

你可以做的是首先创建一个函数,它将像这样返回由 codeigniter 生成的 CSRF 令牌

public function get_csrf()
{

    $error['csrf_token'] = $this->security->get_csrf_hash();
    echo json_encode($error);
    die();
}

然后在 ajax 调用中首先获取此令牌,然后将此令牌与您的 ajax 调用一起发送,如下所示。 //第一个ajax调用获取csrf令牌

$.ajax({
'async': true,
'type': "GET",
'dataType': 'json',
//first ajax url to get csrf token
'url': "<?php echo base_url('main/get_csrf'); ?>",
'success': function (data) {
    tmp = data;
    csrf_token = data.csrf_token;

    //your second ajax call will contain one parameter i.e your csrf token name for eg 'csrf_test_name'
    $.ajax({
        'async': true,
        'type': "POST",
        'dataType': 'json',
        'data': {'email': email, 'social_media_name': 'google', 'csrf_test_name': csrf_token},
        //the url to your controller function
        'url': "<?php echo base_url('social/google_login'); ?>",
        'success': function (data) {
        }
    });
}

});

这适用于我的情况。经过测试。

【讨论】:

  • 为我工作。谢谢!。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2011-11-12
  • 2012-02-03
相关资源
最近更新 更多