【问题标题】:csrf token is changing where it shouldn't be changedcsrf 令牌正在更改不应更改的位置
【发布时间】:2021-05-06 05:27:17
【问题描述】:

我在下面运行代码来防止 CSRF 漏洞

if (!isset($_POST['_token'])) {
    $_SESSION['_token'] = bin2hex(random_bytes(20));
}

我正在使用名为 _token 的隐藏输入中的令牌。我在 main.js 文件中使用以下代码,以便用户可以将产品添加到他们的收藏夹中。

const wishlist = {
    'add': function (id) {
        $.ajax({
            url: 'api/wishlist?method=add',
            type: 'post',
            dataType: 'json',
            data: 'id=' + id + '&_token=' + $('input[name="_token"]').val(),
            success: function (response) {
                 console.log(response)
            }
        })
    },
    'remove': function (id) {
        $.ajax({
            url: 'api/wishlist?method=remove',
            type: 'post',
            dataType: 'json',
            data: id,
            success: function (response) {
                console.log(response)
            }
        })
    }
};

下面是 ajax 请求发送到的 wishlist.php 中的代码

<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    header('Location:' . site_url('404'));
}
if (!isset($_POST['_token']) or $_POST['_token'] != $_SESSION['_token']) {
    die('Invalıd CSRF Token!');
}

if ($_GET['method'] == 'add') {
    $json['method'] = "adding to favorites";
}
if ($_GET['method'] == 'remove') {
    $json['method'] = "removeing from favorites";
}

所有代码都是这样,但有时此代码有效,有时它会给出 Invalid csrf token 错误,有时它会工作 3-5 次并再次出错。

【问题讨论】:

  • wishlist.php 中的错字$_SESION['_token'] 是不是仅在示例中或在实际代码中进行相等检查?
  • 那不在我更新它的实际代码中
  • 你在使用 Laravel 吗?
  • 不,我没有使用任何框架,问题出在 init.php $_SESSION['_token'] = bin2hex(random_bytes(20));即使有 $_POST['_token'] 也会执行,但我不知道为什么
  • 使用 session_start();

标签: javascript php ajax


【解决方案1】:

我找到了解决方案。这是因为客户端试图访问一个不存在的文件 以便该请求执行 init.php

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 2018-10-11
    • 2018-03-02
    • 2013-08-01
    • 1970-01-01
    • 2016-05-17
    相关资源
    最近更新 更多