针对已知的 URL 验证 $_SERVER["HTTP_REFERER"] 是否安全?

Is validating $_SERVER["HTTP_REFERER"] against a known URL safe?

我即将创建一个新网站,我担心潜在的安全漏洞。我关注的是其他人使用我的 PHP 脚本的可能性(据我所知,使用 CORScURL 等方法是可能的——我错了吗?) .

我刚刚四处搜索,发现您可以使用 PHP 的 $_SERVER["HTTP_REFERER"] 来检查发送它的 URL。

SO 上有很多问题,例如 this one and this one 关于 $_SERVER["HTTP_REFERER"] 的使用和安全性。

许多答案类似于 this one(如下所示),表示它不安全,因为软件经常将其删除:

It may be safe, but it is not reliable: due to the HTTP spec, HTTP_REFERER is optional (some clients don't send this header at all, and some "security" software strips this out from any HTTP request), and there are numerous ways to modify this header. Some browsers send the referring page, some send a blank string, some don't send this at all, some may send bogus data, some may send Aunt Matilda; and moreover, you can't tell whether you're getting valid data in this header or not.

So, no, I would never trust that HTTP_REFERER contains the previous page, and neither should you.

但它们大多只是暗示引用者信息可能只是被遗漏/缺失/不完整,但并没有错。

因此,像这样使用它是否安全:

<?php
    if($_SERVER["HTTP_REFERER"] != "my_http_referer.php") {
        die("You cannot access this script.");
    }
?>

即使 $_SERVER["HTTP_REFERER"] 是可选的并且可能不完整,这难道不是 安全的 吗?如果不是我自己的任何脚本调用它,它不应该 die() 吗?还是我忽略了什么?

如果网络应用安全是您最关心的问题,您应该使用一些其他机制来确保请求确实来自您自己的其他页面。你引用的答案很好解释。你不应该只相信 HTTP_REFERER。

如果你想设置一些其他的识别令牌,你可以使用sessionStorage。然后在每次提交表格时阅读。每次收到请求时交叉检查。如果你想要更多的非预测行为,你可以继续改变它。

这有意义吗?