反CSRF会话令牌脚本PHP逻辑问题

时间:2018-09-04 10:20:05

标签: php security webforms

我觉得这是一个逻辑问题。在页面加载时,我正在调用token.php,它应该设置一个会话令牌并用相同的令牌填充一个隐藏字段。 提交我的Web表单时,它会先比较令牌,然后再将信息发送给我。目的是防止CSRF攻击。因为我对PHP(以及js,jQuery,HTML,编码和许多其他东西)非常陌生,所以找不到错误。

我收到“令牌无效”回复。它应该为两个变量设置相同的标记,并且我正在处理带有另一个错误消息的空白标记。

在我的index.html开头

source_file.cpp(20): error C2923: 'Bar': 'Func' is not a valid template type argument for parameter 'T'
source_file.cpp(1): note: see declaration of 'Func'
source_file.cpp(20): error C2990: 'Bar': non-class template has already been declared as a class template
source_file.cpp(13): note: see declaration of 'Bar'
source_file.cpp(20): error C2946: explicit instantiation; 'Bar' is not a template-class specialization  

token.php

<script>
    $(document).ready(function() {
        $.get('token.php').done(function(data) {
            $('input[name="token"]').val(data);
        }).fail();
        {
        //failure code goes here
        }
    });
</script>

formsubmit.php

<?php
session_start();
    if (empty($_SESSION['token'])) {
        $_SESSION['token'] = bin2hex(random_bytes(32));
    }
    $token = $_SESSION['token'];
?>

1 个答案:

答案 0 :(得分:1)

您不会从token.php返回任何信息

<?php

session_start();
if (empty($_SESSION['token']))
    $_SESSION['token'] = bin2hex(random_bytes(32));
echo ($_SESSION['token']);

顺便说一句,如果您仅在该页面中使用php代码,请不要关闭<?php标签,那样可以避免发送空格/换行符作为响应。

在您的jquery中,fail()方法无法按预期工作,因为它后面是分号而不是匿名函数调用。

<script>
    $(document).ready(function() {
        $.get('token.php').done(function(data) {
            $('input[name="token"]').val(data);
        }).fail(function()
        {
            //failure code goes here
        });
    });
</script>

要处理存储在会话中的令牌,请不要忘记在formsubmit.php的开头添加:

<?php 
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
    //Your code
}