1

I'm trying to securely keep a user logged in using php but am worried about security.

So I've been going by this question/answer. But There's still a few things I don't quite understand. Please keep in mind I'm not an expert by any means, so please speak as if you were talking to a child.

function onLogin($db, $user) {
  $token = GenerateRandomToken($db); // generate a token, should be 128 - 256 bit
  storeTokenForUser($db, $user, $token);
  $cookie = $user . ':' . $token;
  $mac = hash_hmac('sha256', $cookie, 'SECRET_KEY');
  $cookie .= ':' . $mac;
  setcookie('rememberme', $cookie, time() + (86400 * 7));
}

My question is, how is this secure? I will be storing it in a cookie, which under my knowledge is viewable by users. The "SECRET_KEY" in hash_hmac must have something to do with it but I didn't find much information on how to use it in the manual.

Will the "SECRET_KEY" in hash_hmac be the way that I can secure my cookies? If so, how do I use it? Will it be the same everytime? or should I generate a random ID for it?

Thanks for your time. Greatly appreciated.

Community
  • 1
  • 1
Mathew
  • 117
  • 6
  • 2
    Didn't look too closely at the specific code, but in general with this type of thing: You better make sure you are checking for session hijacking attempts, and also deleting the token from your db when an expiration date/time passes (i.e. expiration date in table and delete all rows which passed theirs). – developerwjk Dec 17 '14 at 00:16

0 Answers0