且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在PHP中设计安全的自动登录Cookie系统

更新时间:2023-12-04 19:34:16

你想要这个臭名昭着的cookie越安全,越麻烦您。如果您的用户应该特别安全,您必须使用最麻烦的方法。

The more secure you want this infamous cookie, the more trouble it's going to be for you. If your users should be particularly secure, you will have to go with the most troublesome approach.

您应该只接受这个cookie与https,如果你想要安全可能。如果通过http接受cookie,它可以被嗅探和被盗。

You should only accept this cookie with https if you want to be as secure as possible. If the cookie is accepted over http, it can be sniffed and stolen.

我建议cookie没有用户数据(一个令牌,如你所建议的) 。不幸的是,这将需要另一个表。当用户登录并选择保持登录时,在此表中创建一个条目。该条目可以是任何无意义的值(例如 md5(uniqid('',true)); 。此令牌在DB中可以是唯一的,并映射到用户的ID。

I would recommend that the cookie have no user data at all (a token, as you suggested). This will, unfortunately, require another table. When a user logs in and chooses "keep login," create an entry in this table. The entry can be any meaningless value (such as md5(uniqid('', true));. This token can be unique in the DB and mapped to a user's ID.

当用户访问您的网站时,您可以检查该Cookie的值,并获取其所属的用户并登录。此时,令牌并创建一个新的Destroy可能意味着许多事情,你可以从数据库中完全删除它,或者有一个标志禁用令牌。你可能希望允许相同的令牌多次使用,但是我认为这是不安全的,你可能还想存储令牌的时间戳,只有在一段有限的时间(例如30天)后才接受它。

When a user visits your website, you can check the value of that cookie and get the user it belongs to and log them in. At this point, you destroy the old token and create a new one. "Destroy" can mean many things. You can delete it from the DB entirely or have a flag that disables the token. You may want to allow the same token to be used multiple times in case the cookie is received but the authentication doesn't go through for some reason, but I think this is insecure. You may also want to store the timestamp of the token and only accept it if it's been some limited period of time (30 days for example).

正如您的朋友指出,您可以存储其他信息,例如用户代理,IP地址等,但即使使用相同的浏览器,这些信息也可能会更改与移动),如果用户的持久登录不被接受,因为这可能是刺激和不方便他们。

As your friend points out, you can store other information such as user agent, IP address, etc., but these may change even with the same browser being used (especially with mobile) and if a user's persistent login is not accepted because of this, it could be jarring and inconvenient to them.

如果你真的不想创建另一个表,那么您将必须存储一些方法来从cookie值获取用户的ID。这不太安全。

If you really don't want to create another table, then you will have to store some way to acquire the user's ID from the cookie value. This is less secure.