如何(安全地)存储cookie,并在用户重新打开浏览器时保持登录状态?


How do I store a cookie (securely) and keep the user logged in when they re-open a browser

如何安全地将用户的密码存储在cookie中,同时仍然能够访问该密码?我有一个cookie,存储的用户名和密码的sha1版本,但当我试图检索他们,我得到(如预期的)用户名和密码的sha1版本,而不是密码本身。谢谢!

<!DOCTYPE html>
<html>
  <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
  </head>
<body>
<form id='my_login' name='my_login' action='<?php htmlentities($_SERVER['PHP_SELF'])?>' method='post' accept-charset='UTF-8'>
<input type='hidden' name='submitted' id='submitted' value='1'/>
 <label for='username'>Username: </label>
 <input id='username' type='text' name='username' value='<?php if(isset($_COOKIE['username'])) echo htmlentities($_COOKIE['username']); ?>'/>
 <br/>
 <label for='username'>Password: </label>
 <input id='password' type='password' name='password' value='<?php if(isset($_COOKIE['password'])) echo htmlentities($_COOKIE['password']); ?>'/>
 <br/>
  <label for "set_cookie">Remember Me</label>
 <input type="checkbox" name="set_cookie" id="set_cookie" value="1"/>
 <button id='submit' type='submit' name='submit'>login</button>
   </form>
  </body>
  <html>

如何安全地将用户的密码存储在cookie中

永远不要在本地存储用户的密码。即使在使用目前被认为是安全的加密时,您也会打开一个巨大的潜在安全漏洞,因为您正在为可能的攻击者在许多许多客户机上传播数据。

给用户一个带有随机会话ID的长期cookie。为该会话设置一个遥远的过期时间(无限期地存储它并不是一个好主意)。许多网站将其限制为30天。)让该ID自动在服务器上登录用户。

另外,当您使用php setcookie时,请确保将最后一个参数httponly添加为true。

httponly

当TRUE时,cookie将只能通过HTTP协议访问。这意味着cookie不能被脚本语言(如JavaScript)访问。有人建议,这种设置可以有效地帮助减少通过XSS攻击进行的身份盗窃(尽管并非所有浏览器都支持这种设置),但这种说法经常受到争议。在PHP 5.2.0中添加。TRUE或FALSE

来源:PHP setcookie

这将减少cookie被JavaScript劫持的可能性。

如果您有能力,您也可以设置secure标志,只通过https发送cookie