我想我的网站有一个复选框,用户可以点击,这样他们就不必每次访问我的网站时登录。我知道我需要在他们的电脑上存储一个cookie来实现这个功能,但是这个cookie应该包含什么呢?

此外,是否有一些常见的错误需要注意,以防止这个cookie出现安全漏洞,而这可以在提供“记住我”功能的同时避免?


当前回答

改进的持久登录Cookie最佳实践

你可以使用这里描述的最佳实践(2006年)或这里描述的更新策略(2015年):

When the user successfully logs in with Remember Me checked, a login cookie is issued in addition to the standard session management cookie. The login cookie contains a series identifier and a token. The series and token are unguessable random numbers from a suitably large space. Both are stored together in a database table, the token is hashed (sha256 is fine). When a non-logged-in user visits the site and presents a login cookie, the series identifier is looked up in the database. If the series identifier is present and the hash of the token matches the hash for that series identifier, the user is considered authenticated. A new token is generated, a new hash for the token is stored over the old record, and a new login cookie is issued to the user (it's okay to re-use the series identifier). If the series is present but the token does not match, a theft is assumed. The user receives a strongly worded warning and all of the user's remembered sessions are deleted. If the username and series are not present, the login cookie is ignored.

这种方法提供了纵深防御。如果有人设法泄露了数据库表,也不会给攻击者冒充用户的机会。

其他回答

我自己调查了持久会话,发现它根本不值得冒安全风险。如果一定要使用它,但是应该考虑这样的会话只进行弱身份验证,并强制任何可能对攻击者有价值的东西进行新登录。

原因当然是,包含持久会话的cookie很容易被窃取。

偷饼干的4种方法(来自Jens Roland在@splattne页面上的评论):

通过不安全的线路拦截它(包嗅探/会话劫持) 通过直接访问用户的浏览器(通过恶意软件或物理访问盒子) 通过从服务器数据库读取它(可能是SQL注入,但可以是任何东西) 通过XSS黑客(或类似的客户端漏洞)

存储他们的UserId和一个RememberMeToken。当他们登录时,“记住我”勾选生成一个新的“记住我”令牌(使任何其他标记为“记住我”的机器无效)。

当它们返回时,通过remember me令牌查找它们并确保UserId匹配。

我将存储一个用户ID和一个令牌。当用户返回站点时,将这两段信息与数据库条目等持久性信息进行比较。

至于安全性,不要在里面放任何会允许别人修改cookie以获得额外好处的东西。例如,不要存储他们的用户组或密码。任何可以修改并规避您的安全性的内容都不应存储在cookie中。

改进的持久登录Cookie最佳实践

你可以使用这里描述的最佳实践(2006年)或这里描述的更新策略(2015年):

When the user successfully logs in with Remember Me checked, a login cookie is issued in addition to the standard session management cookie. The login cookie contains a series identifier and a token. The series and token are unguessable random numbers from a suitably large space. Both are stored together in a database table, the token is hashed (sha256 is fine). When a non-logged-in user visits the site and presents a login cookie, the series identifier is looked up in the database. If the series identifier is present and the hash of the token matches the hash for that series identifier, the user is considered authenticated. A new token is generated, a new hash for the token is stored over the old record, and a new login cookie is issued to the user (it's okay to re-use the series identifier). If the series is present but the token does not match, a theft is assumed. The user receives a strongly worded warning and all of the user's remembered sessions are deleted. If the username and series are not present, the login cookie is ignored.

这种方法提供了纵深防御。如果有人设法泄露了数据库表,也不会给攻击者冒充用户的机会。