【发布时间】:2012-12-07 08:30:42
【问题描述】:
我试图阻止用户直接访问我的POST/AJAX 文件。我决定创建一个随机令牌,我称之为“nonce_key”。该密钥是使用SESSION 创建的,然后我通过POST 传递它。如果SESSION 密钥与POST 相同,那么我允许访问。问题是有时它不起作用。
这是我的工作流程:
我的 index.php 上有一个选择,当用户更改其值时,它通过 ajax 调用“change_status.php”。
由于某种原因,index.php 上设置的 SESSION 键值与 change_status.php 上的 SESSION 键值不同。
我的functions.php文件中有以下代码
function nonce_key()
{
return hash('crc32b', time());
}
然后在我的索引中我有
session_start();
require_once 'functions.php';
$_SESSION['nonce_key'] = nonce_key();
echo '
<script type="text/javascript">
$"#change_status").bind("change",function() {
var form_data = {
nonce: "'.$_SESSION['nonce_key'].'",
id: $("#id").val(),
};
$.ajax({
type: "POST",
url: "change_status.php",
data: form_data,
success: function(result) {
$("#message").slideDown("slow").html(result);
}
});
});
</script>'
;
最后在我的 change_status.php 文件中
session_start();
require_once 'functions.php';
if(isset($_SESSION['nonce_key']) && isset($_POST['nonce']))
{
if($_SESSION['nonce_key'] == $_POST['nonce'])
{
change_app_status($_POST['id']);
} else echo 'Nonce Invalid';
} else echo 'Not Allowed';
【问题讨论】:
-
对我来说很合适。还有其他可能影响会话值的东西吗?为什么要逃避 jQuery 中的 \'change\' 事件?由于您(赞赏)只显示您的相关代码,是否还有其他语法错误? nonce_key 会被发布吗?它们有何不同?
-
你的
index中有一个奇怪的 php 和 js 组合,你能在 html 的源代码中检查 javascript 的原样吗? -
“不起作用”是什么意思?你得到“不允许”还是“Nonce Invalid”或其他什么?
-
@OlafDietsche 我在进行一些调试时得到“Nonce Invalid” 我看到 change_status.php 上的 $_SESSION['nonce_key'] 不同于 index.php 我不明白它为什么会改变在 change_status.php 上,因为我只在 index.php 上声明值
-
@jtheman 我更改了代码以使其更有意义。但是是的,某些东西必须改变会话值,但我不知道是什么或如何。我只在页面开头给会话赋值。
标签: php ajax security session csrf