douchujian8124 2018-10-01 04:57 采纳率: 100%
浏览 86

执行AJAX时令牌验证的问题。 CSRF(PHP)查询

The problem is to validate the token when the Ajax request is executed. I can’t understand where I made a mistake.

Catalog list:
   /ajax/test.php
   /core/csrf.php
   /index.php

File csrf.php

<?php
class ag_csrf{
  public $last_token;
  public $tkn;
  private $ses_name;

  function __construct($ses_name = 'csrf_token')
  {
    $this->ses_name = $ses_name;
    if(isset($_SESSION[$this->ses_name])) $this->last_token = $_SESSION[$this->ses_name];
    $this->tkn = $this->gen_token();
  }

  public function gen_token(){
    $tkn = sha1('-defender'.openssl_random_pseudo_bytes(30).session_id());
    $_SESSION[$this->ses_name] = $tkn;
    return $tkn;
  }
  public function check_token($token=''){
    $c = ($token === $this->last_token) ? true : false;
    return $c;
  }
  public function get_token(){
    return $this->tkn;
  }
  public function meta($name = 'csrf-token'){
    return '<meta name="'.$name.'" content="'.$this->tkn.'" />';
  }
  public function form($name = 'hash'){
    return '<input type="hidden" name="'.$name.'" value="'.$this->tkn.'">';
  }
  //$csrf->get_token();
  //$csrf->check_token($_POST['hash'])
}
?>

AJAX file (test.php):

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
  require_once($_SERVER["DOCUMENT_ROOT"].'/core/csrf.php');
    $csrf = new ag_csrf;

    $csrf_post = $_POST['csrf'];
    if($csrf->check_token($csrf_post)){
        //code

        echo json_encode(array("status" => "1", "text" => "kek good!", "post" => $_POST['csrf']));
    }else{
        echo json_encode(array("status" => "3", "text" => "csrf", "post" => $_POST['csrf']));
    }
}
?>

index.php

<?php
  ini_set('error_reporting', E_ALL);
  ini_set('display_errors', 1);
  ini_set('display_startup_errors', 1);

  session_start();

  require_once($_SERVER["DOCUMENT_ROOT"].'/core/csrf.php');
  $csrf = new ag_csrf;

  if(isset($_POST['go'])){
    if( $csrf->check_token($_POST['hash']) ){
      echo 'Ok';
    }else{
      echo 'CSRF Err';
    }
  }
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <?=$csrf->meta();?>
</head>
<body>
  <form method="post">
    <input type="text" name="usr" value="" />
    <?=$csrf->form();?>
    <input type="submit" name="go" />
  </form>

  <hr />
  <p></p>
  <button type="button" class="uj">Ajax</button>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script>
    var csrf = $('meta[name="csrf-token"]').attr('content');

    $('.uj').click(function(){
      $.ajax({
        url: "/ajax/test.php",
        type: "POST",
        data: ({csrf:csrf}),
        dataType: "html",
        beforeSend: function(request){
          $('p').html("Обновление данных...");
        },
        success: function(data){
          console.log(data);
          data = JSON.parse(data);

          if(data['status'] == "3"){
            $('p').html(data['text']);
          }else{
            $('p').html(data['text']);
          }
        }
      });
    });
  </script>
</body>
</html>

The validation of forms passes on hurray, and here at performance of Ajax request tokens do not converge. Where is the puncture?

I think that because of the re-loading of the csrf.php file in test.php, new tokens are generated and this request does not pass the validation. What can be done?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安装svn网络有问题怎么办
    • ¥15 Python爬取指定微博话题下的内容,保存为txt
    • ¥15 vue2登录调用后端接口如何实现
    • ¥65 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥15 latex怎么处理论文引理引用参考文献