5

What's the best and most secure way to go when writing an authentication library in a model-view-controller way?

The things that give me a hard time are keeping track of the users activity and remembering users via a cookie or storing sessions in the database?

Thanks in advance :).

montrealist
  • 5,593
  • 12
  • 46
  • 68
  • You should re-use an existing authentication framework whenever possible, because, really, it's complex. For example, take a look at https://github.com/delight-im/PHP-Auth which is both framework-agnostic and database-agnostic. – caw Oct 21 '16 at 21:34

2 Answers2

4

If you want to use sessions, you have secure them against attacks like session fixation and session hijacking.

To prevent both you have to ensure that only authenticated requests are allowed to use the session. This is commonly done by chaining as many specific (possibly unique) informations about the client as possible with the session. But as some informations may change on every request (like the IP address), it can be difficult to find good one.
This is why it is useful to use the method denoted as Trending.

Another good protection measure is to swap the session ID periodically. Thus the period for an attack on a valid session ID is smaller.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
3

The simplest way to implement it is with PHP SESSIONS.

just session_start (); near the beginning of your script and you have access to the $_SESSION global array for holding your authentication data.

Depending on the configuration of your server all the data stored in $_SESSION will only be available on the server from which it is hosted (with few exceptions). You can configure it to be saved in a temporary directory, in memcached, or even a database.

The only thing that is transmitted between the client and your server is a "session key". The key can be passed by cookie or URL-rewrites (which are transparently handled by the start_session output buffer).

Nolte
  • 1,096
  • 5
  • 11
  • Thanks. But how can i keep track of users activity and how can i give users an option to stay logged in for 1 month? Which things should i store in the database, session or cookie? And what's the best way to check if everything is ok? –  Jan 24 '09 at 10:31
  • That would be something to explicitly set in a cookie with an additional hash, then in the DB store the IP, if the user logs in from a different ip or the hash in the cookie does not match one in the db then require the user to login again. – UnkwnTech Jan 24 '09 at 10:43
  • You can just have a check that invalidates the session after session_start() if a timestamp stored in the session array is beyond a certain age. Then you wouldn't have to deal with cookies at all. – Nolte Oct 22 '10 at 20:35