Best way for authentication in PHP
Asked Answered
S

2

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 :).

Sikes answered 24/1, 2009 at 10:14 Comment(1)
You should re-use an existing authentication framework whenever possible, because, really, it's complex. For example, take a look at github.com/delight-im/PHP-Auth which is both framework-agnostic and database-agnostic.Sweettalk
K
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.

Kiersten answered 24/1, 2009 at 12:3 Comment(0)
S
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).

Scurrile answered 24/1, 2009 at 10:27 Comment(3)
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?Sikes
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.Morsel
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.Scurrile

© 2022 - 2024 — McMap. All rights reserved.