猿问

用于自动登录用户的 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');

        }

    }


慕田峪4524236
浏览 271回答 2
2回答

慕慕森

假设您在 cookie 中存储了攻击者可能猜到的东西(如username=bob或admin=true),这确实是不安全的。cookie 由客户端发送到服务器,攻击者可以干扰发送到服务器的 cookie(通过在浏览器中更改此设置或手动发送 http 请求)。因此,他可以发送他想要发送的任何 cookie,例如发送带有admin=true.另一方面,会话的内容存储在服务器端,用户无法操作。

catspeake

我不知道我的方式有多专业,但我正在使用它:您可以在您的数据库的用户表中为标识符创建一列。每次用户成功登录时,您可以创建一个随机散列并更新他在 DB 中的记录,将此散列作为他的标识符,并使用标识符散列为他设置一个 cookie。因此,下次用户打开您的网站时,您可以检查是否设置了 cookie,如果是,您可以在您的数据库中搜索具有该标识符的记录,如果找到,则获取该记录并放入会话并在您的脚本中使用它。此外,每次用户注销并再次登录时,标识符都是一个新的哈希值。所以没有人可以猜测另一个用户标识符设置为 cookie 并执行 CSRF 攻击。<?php&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// example for creating a random string as identifier :&nbsp; &nbsp; &nbsp; &nbsp; $randomByte = random_bytes(15);&nbsp; &nbsp; &nbsp; &nbsp; $identifier = bin2hex($randomByte);&nbsp; &nbsp; &nbsp; &nbsp; setcookie('identifier', $identifier, (time() + 86400 * 30),'');&nbsp; &nbsp;// example for remembering user&nbsp;&nbsp; &nbsp; if (isset($_COOKIE['identifier']) && !is_null($_COOKIE['identifier']) && !empty($_COOKIE['identifier']) && !isset($_SESSION['userSignedIn'])) {&nbsp; &nbsp; &nbsp; &nbsp; $cachedIdentifier = $_COOKIE['identifier'];&nbsp; &nbsp; &nbsp; &nbsp; $userFoundByID = $usersInstance::selectByIdentifier($cachedIdentifier);&nbsp; &nbsp; &nbsp; &nbsp; if (!empty($userFoundByID) && !is_null($userFoundByID)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $user = $userFoundByID[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $_SESSION['userSignedIn'] = $user;&nbsp; &nbsp; &nbsp; &nbsp; }?>
随时随地看视频慕课网APP
我要回答