How to ensure the security of cookie automatic login

Excerpted from Dewen Network http://www.dewen.org/q/6364

method one:
The user's authentication information is guaranteed in a cookie, as follows:
1. cookie name: uid. Encryption is recommended, such as MD5 ('site name'), etc.
2. cookie value: login name|valid time Expires|hash value. The hash value can be "login name + valid time Expires + the first few digits of user password (encrypted) + salt", salt is a random number guaranteed in the server-side site configuration file.
This design has the following advantages:
1. Even if the database is stolen, the thief cannot log in to the system, because the salt that constitutes the cookie value is guaranteed to be in the server site configuration file rather than the database .
2. If the account is stolen and the user changes the password, the cookie value of the thief can be invalidated.
3. If the database on the server side is stolen, the cookie value of all users can be invalidated by modifying the salt value, forcing the user to log in to the system again.
4. The valid time Expires can be set to the current time + past time (such as 2 days), which can ensure that the cookie value of each login is different, preventing thieves from snooping on their own cookie value as a backdoor and logging in for a long time.

Method Two:
After each user logs in, a random GUID is generated, and then the GUID is stored in the database (you can also consider using Redis to store the user information and random GUID in the form of KEY-VALUE GUID-user information, and set a timeout when storing, such as 20 minutes , every time the user information is verified, it will be automatically extended by 20 minutes . If the user chooses to remember to log in, the set time is 30 days). If the security requirements are high, the GUID will be , and the old one will be invalidated, so that the old remembered login will be automatically invalidated after logging in in a new place. If the security requirements are low, the same can be returned every time until the old GUID is invalidated after the user changes the password. There is no content directly related to the user name and password in the user's cookies. Even if the cookies are stolen, the password cannot be changed. After the original user finds that the account is abnormal, he only needs to change the password to prevent the theft of the account.

Another: To prevent XSS attacks, you can set Http-Only to True.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325550307&siteId=291194637