这是我的PHP
代码。
<?php
$username = "admin";
$password = "admin";
$session = $_COOKIE['session'];
$private_key = "!$//%$$//%$&=§$!&%&=§$!&%";
if(isset($_POST['login'])) {
if($_POST['username'] == $username && $_POST['password'] == $password) {
setcookie("username", $username, time()+(10*365*24*60*60));
setcookie("session", md5($password.$private_key), time()+(10*365*24*60*60));
echo "You are are logged in!";
} else {
echo "Wrong login!";
}
}
if(isset($_COOKIE['session'])) {
if($_COOKIE['username'] == $username && $_COOKIE['session'] == md5($password.$private_key)) {
echo "You are are logged in!";
} else {
echo "Wrong login!";
}
}
?>
<form method="post" action="">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login">
</form>
此代码的作用:当您使用正确的数据登录时,将使用用户名和哈希密码设置cookie。用户名不是秘密,可以以明文形式存储。在散列之前,密码与一个神秘的字符串相结合,以防止有人猜出密码。如果不了解$private_key
,他就不会有成功。
重新访问该页面时,您已经因为cookie而登录。
当然我的剧本并不完美,但是:这是正确的方法吗?
如果没有正确的登录数据,您将无法登录。黑客也无法找到密码,因为它与一个神秘的字符串结合在一起。
但是黑客可以通过某种方式读取cookie数据,并且只能通过操纵浏览器中的cookie数据来使用cookie数据登录。我该怎样预防呢?
如果您正在尝试实现“在此计算机上记住我”功能(即会话之上的持久身份验证),您将要进入一个复杂的名副其实的兔子洞。我建议阅读this dedicated guide的主题。
总结策略:不要将密码存储在cookie中(散列或其他方式)。相反,您将使用随机生成的令牌。具体来说,一个split token。
<?php
class Authentication
{
/** @var PDO $db */
private $db;
public function __construct(PDO $pdo)
{
$this->db = $pdo;
}
public function createLongTermToken(int $userId = 0): string
{
// Build the components
$tokenLeft = base64_encode(random_bytes(15));
$tokenRight = base64_encode(random_bytes(33));
$tokenRightHashed = hash('sha256', $tokenRight);
// Insert into the database
$stmt = $this->db->prepare(
"INSERT INTO auth_tokens (user_id, selector, hash) VALUES (?, ?, ?)"
);
$stmt->execute([$userId, $tokenLeft, $tokenRightHashed]);
return $tokenLeft . ':' . $tokenRight;
}
public function loginWithPersistentCookie(string $cookieValue): int
{
// Input validation
if (strpos(':', $cookieValue) === false) {
throw new Exception('Invalid authentication token');
}
list($tokenLeft, $tokenRight) = explode(':', $cookieValue);
if (strlen($tokenLeft) !== 20) || strlen($tokenRight) !== 44) {
throw new Exception('Invalid authentication token');
}
$tokenRightHashed = hash('sha256', $tokenRight);
// Fetch from database
$stmt = $this->db->prepare("SELECT * FROM auth_tokens WHERE selector = ?");
$stmt->execute([$tokenLeft]);
// Now our token data is stored in $row:
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// Delete token after being retrieved
$stmt = $this->db->prepare("DELETE FROM auth_tokens WHERE selector = ?");
$stmt->execute([$tokenLeft]);
// Verify the right hand side, hashed, matches the stored value:
if (!hash_equals($row['hash'], $tokenRightHashed)) {
throw new Exception('Invalid authentication token');
}
return $row['user_id'];
}
}
用法:
// Post-authentication, before headers are sent:
$cookieValue = $auth->createLongTermToken($userId);
setcookie(
'long_term_auth',
$cookieValue,
time() + (86400 * 30), // 30 days
'',
'',
TRUE, // Only send cookie over HTTPS, never unencrypted HTTP
TRUE // Don't expose the cookie to JavaScript
);
在页面加载:
if (!isset($_SESSION['user_id']) && isset($_COOKIE['long_term_auth'])) {
try {
$_SESSION['user_id'] = $auth->loginWithPersistentCookie($_COOKIE['long_term_auth']);
} catch (Exception $ex) {
// Security error! Handle appropriately (i.e. log the incident).
}
}
上面的代码片段假设$auth
是示例Authentication
类的一个实例。它还假设auth_tokens
的基本表结构(user_id
指向users表,selector
和hash
是VARCHAR或TEXT字段,在selector
上有唯一约束)。
random_bytes()
生成安全令牌。hash_equals()
来比较哈希。==
而不是hash_equals()
来比较哈希。另见:magic hashes。此外,您将需要使用password_hash()
和password_verify()
进行实际的用户身份验证步骤。这只是描述了“记住我”复选框便利功能的安全实现。
为了更好的安全性,您可能希望使用password_exposed
和/或zxcvbn之类的东西来防止使用弱/泄密密码。
您的用户将希望使用密码管理器(如KeePassXC,1Password或LastPass)为您的网站生成/存储其密码,这样他们就不会使用admin
等弱密码。