【问题标题】:Ajax CSRF 403 forbidden codeigniterAjax CSRF 403 禁止代码点火器
【发布时间】:2015-12-05 08:26:58
【问题描述】:

您好,我正在调用控制器以在启用 CSRF 的基于 codeigniter 的应用程序中使用 AJAX 获取部分

我的 ajax 代码

    $('#classes').change(function(){  
  $classes=$(this).val();
            $.ajax({
             type:"POST",
             data:{
                 '<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>',
                 'class':$classes
             },
             url:"<?php echo base_url();?>index.php/admin/getsection/"+$classes,
             success:function(return_data)
             {
                //alert(return_data);
                $('#section').html('');
                $('#section').html(return_data);
                $('#section').val(section);
             }
    });

当我第一次调用 ajax 函数时,它会完美运行。但是当我再次运行相同的函数时,它会返回 403 禁止错误。

请指教我的工作

【问题讨论】:

    标签: php jquery ajax codeigniter csrf


    【解决方案1】:

    来自the docs

    令牌可以在每次提交时重新生成(默认),也可以在 CSRF cookie 的整个生命周期内保持不变。令牌的默认重新生成提供了更严格的安全性,但由于其他令牌变得无效(后退/前进导航、多个选项卡/窗口、异步操作等),可能会导致可用性问题。您可以通过编辑以下配置参数来更改此行为

    $config['csrf_regenerate'] = TRUE;
    

    将其设置为 FALSE。

    【讨论】:

      【解决方案2】:
      ur controller should be like this 
      
       function reply(){       
              $insert = $this->Message_model->send_message2();
              $csrf = $this->security->get_csrf_hash();
      if($this->input->is_ajax_request())
      {
         header("Content-type: application/json; charset=utf-8");
      echo json_encode(array("data" => $insert,'csrf'=> $csrf)); 
      }
      
      
      
      
      ur jquery should be this way
      
      var token = data.csrf;
      
      $.ajax({
          url: '/next/ajax/request/url',
          type: 'POST',
          data: { new_data: 'new data to send via post', csrf_token:token },
          cache: false,
          success: function(data, textStatus, jqXHR) {
              // Get new csrf token for next ajax post
              var new_csrf_token = data.csrf     
             //Do something with data returned from post request
          },
          error: function(jqXHR, textStatus, errorThrown) {
            // Handle errors here
            console.log('ERRORS: ' + textStatus + ' - ' + errorThrown );
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2016-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 1970-01-01
        • 2016-05-08
        • 2015-07-30
        • 2018-01-14
        相关资源
        最近更新 更多