PHP Storing Current Session IDs in Database using

2019-02-25 06:35发布

问题:

I've created a login system that uses cookies and stores a session ID in a database, so your login will only work with that particular session ID. I realise this has a few problems:

  1. If you login on another device the session ID changes (no multi logins)
  2. The session ID is really the only thing identifying the user as logged in (I'm not really sure if this is a security risk since the cookie is domain specific)

However I want to retain the persistant login that comes with cookies while still keeping stuff secure.

Effectively I want to know if there is a better way to securely log a user into a website using cookies.

回答1:

First of all, keeping stuff secure and persistent logins don't go together; you will always compromise security by introducing persistent logins in some way.

Having said that, an article from Charles Miller outlines such a system:

  1. create a (big enough) random key, preferably by using /dev/urandom or openssl_random_pseudo_bytes() and associate it with an account (in database terms: a separate table with the random key as the primary (or unique) index and the account as a foreign key); the key will be the cookie value.

  2. when a non-logged in user presents a cookie, the key and account are looked up and the user is logged in; afterwards, the used key is replaced with a new random key (cookie is updated too).

  3. users who are logged in via cookie alone should be asked for their password again when they access sensitive (account) information.

  4. the user should have an option to log out from all his devices.

It's also a good practice to use a renew the session id using session_regenerate_id() whenever a user is logged in (either via a form or cookie). This prevents someone from launching a session fixation attack against someone else and possibly steal their identity.

An improvement on this design by Barry Jaspen that can also handle identify theft detection can be found here.



标签: php security