Cookie + db token + session authentication, can i do away with the sessions
I have a little web app, which uses a lot of ajax. After someone logs in, what we need to keep persistent is their user_id and group_id
The way I first did authentication, I just stored these as clear txt in cookies ( $_COOKIE['user_id'], $_COOKIE['group_id'] ). Obviously that was bad since you could modify both values!
I'm not an experienced programmer and don't need massively amazing security for this app. But that was pretty bad.
So, I moved on to creating a token in the database, which stores the user_id, group_id and a hash token and t开发者_运维知识库hen putting that token only in the cookie. The user_id and group_id are created as sessions once the token is authenticated (cookie match database).
This is more secure but the whole thing of having to manage the user_id and group_id sessions (timeouts, reinitialising) vs just grabbing them from cookies has caused a lot of grief and made my app's actual functioning less reliable.
Now accepting my level of skill, and that the easy management + robust functioning of my app is more important than high level security... I'm wondering if I could do away with the sessions, and do a compromise by still storing the user_id and group id in a cookie but along with the hash - i.e.
COOKIE['token'] = user_id_val+group_id_val+hash_in_db
would look like: 23-144-jhwr8324398fjk2j49083223n23
So all I need is a little function to parse that string and do everything from that. Someone could change the values but obviously the hash won't match.
Is this ok?
You don't need cookies at all (well, except for the session cookie) for authentication. Here's an example of a simple cookie-less authentication:
session_start();
// $db is a pseudo object for database access
// Verify login
$auth = false;
if (isset($_SESSION['user_id']) && isset($_SESSION['user_hash'])) {
$user = $db->getUserById($_SESSION['user_id']);
if ($user) {
$hash = sha1($user->id.$user->salt);
if ($hash === $_SESSION['user_hash']) $auth = true;
}
}
// Make login
if (isset($_POST['login'])) {
$user = $db->getUserByCredentials($_POST['login'], $_POST['password']);
if ($user) {
$_SESSION['user_id'] = $user->id;
$_SESSION['user_hash'] = sha1($user->id.$user->salt);
// redirect...
}
// redirect to error page
}
Of course, this can be improved to add defence mechanisms against all sorts of attacks, store user information, etc. but this is the basic idea. It's way more secure than using cookies.
精彩评论