首页 > 解决方案 > 用于自动登录用户的 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');
        }
    }

标签: phpcookies

解决方案


假设您在 cookie 中存储了攻击者可能猜到的东西(例如username=bobadmin=true),这确实是不安全的。cookie 由客户端发送到服务器,攻击者可以干扰发送到服务器的 cookie(通过在浏览器中更改或手动发送 http 请求)。因此,他可以发送他想要发送的任何 cookie,例如发送带有 的 cookie 标头admin=true

另一方面,会话的内容存储在服务器端,用户无法操作。


推荐阅读