php - 用于自动登录用户的 cookie 的安全性如何?
问题描述
我知道关于 cookie 的一般安全性还有其他问题,但想知道它们在这种特定情况下的安全性,以及是否有更好的方法来解决它。
我有一个完整的系统,用户可以登录并查看他们所属团队的数据。我正在使用会话,但决定转而使用 cookie,因为这允许用户在返回页面(比如第二天)时自动登录,就像在 facebook 等网站上一样。
我有一个功能,可以在用户进入页面时检查用户计算机上的 cookie,如果他们已经有 cookie,则将其登录(同时刷新管理员 cookie,因为该 cookie 仅持续一天,因为能够删除管理员权限)。我想知道这种方式的 cookie 有多安全,以及是否有人可以操纵 cookie 登录或使自己成为管理员。
function checkForCookies() {
if (isset($_COOKIE["username"])) { // Sees if the user has already got a cookie from logging in recently
if (isset($_COOKIE["admin"])) { // Sees if admin cookie is set as this has a shorter expiry as it is more important if changed
header('Location: ../HomePages/HomePage.php');
}
else {
$tempCon = new DBConnect();
$sql = "SELECT * FROM users WHERE Username = :username";
$stmt = $tempCon->conn->prepare($sql);
$stmt->bindParam(':username', $_COOKIE["username"]);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_OBJ)) {
setcookie("admin", $row->Admin, time() + 86400, "/", "", true, true);
}
header('Location: ../HomePages/HomePage.php');
}
}
else {
header('Location: ../Login/Login.php');
}
}
解决方案
假设您在 cookie 中存储了攻击者可能猜到的东西(例如username=bob
或admin=true
),这确实是不安全的。cookie 由客户端发送到服务器,攻击者可以干扰发送到服务器的 cookie(通过在浏览器中更改或手动发送 http 请求)。因此,他可以发送他想要发送的任何 cookie,例如发送带有 的 cookie 标头admin=true
。
另一方面,会话的内容存储在服务器端,用户无法操作。
推荐阅读
- python - Python创建局部变量而不是使用全局变量
- android-studio - 如何选择一组特定的测试(不在同一个包中)在 Android Studio 中运行?
- c# - 错误 MSB3103:MSBuild 中的 Resx 文件无效
- keycloak - 使用 --backup 选项运行 keycloak slave 时,管理 url 控制台不可用
- python - 看来我不能在另一个带有添加字母的正则表达式中使用具有相同字符的正则表达式
- python - 如何使用 rpy2 解决“无法加载库错误”?
- excel - 使用 vba 确定不同商店的最佳购买产品
- symfony - 如何配置新的 Doctrine 3.0
- database - Kubernetes 卷:什么时候需要 Statefulset?
- javascript - 我如何在 JavaScript Regexp 中检查这样的数字组?