0

I followed this answer for php login system (Remember me) PHP login system: Remember Me (persistent cookie)

I was able to set the cookie successfully using

$selector = base64_encode(random_bytes(9));
$authenticator = random_bytes(33);
$token = hash('sha256', $authenticator);
$expires = date('Y-m-d\TH:i:s', time() + 864000);

$stmt2 = $pdo->prepare("INSERT INTO auth_tokens (selector,token,userid,expires) VALUES (:selector, :token, :userid, :expires)");
$stmt2->bindParam(':selector', $selector);
$stmt2->bindParam(':token', $token);
$stmt2->bindParam(':userid', $userid);
$stmt2->bindParam(':expires', $expires);
$stmt2->execute();

setcookie(
        'remember',
         $selector.':'.base64_encode($authenticator),
         time()+86400,
         '/',
         false
);

I dont seem to understand this part. Re-Authenticating On Page Load

if (empty($_SESSION['userid']) && !empty($_COOKIE['remember'])) {
list($selector, $authenticator) = explode(':', $_COOKIE['remember']);

$row = $database->selectRow(
    "SELECT * FROM auth_tokens WHERE selector = ?",
    [
        $selector
    ]
);

if (hash_equals($row['token'], hash('sha256', base64_decode($authenticator)))) {
    $_SESSION['userid'] = $row['userid'];
    // Then regenerate login token as above
}
}

1. What should be in $selector and $authenticator variables

because from the code, there is a query which says SELECT from auth_tokens where selector = $selector

2. The selector changes everytime on page reload cause its random. So if the $selector = base64_encode(random_bytes(9)); It doesn't match with anything in the selector column when I run this query *"SELECT * FROM auth_tokens WHERE selector = $selector"*

Someone explain the Re-Authenticating On Page Load and some example code.

Ibrahim
  • 99
  • 12

1 Answers1

1

What should be in $selector and $authenticator variables

list($selector, $authenticator) = explode(':', $_COOKIE['remember']);

The cookie contents, set in an earlier visit:

setcookie(…, $selector.':'.base64_encode($authenticator), …);

The selector changes everytime on page reload cause its random.

It shouldn't change on page reload. It should be set once, right after successful sign in, and stored in two places (server database and browser cookies):

if ($login->success && $login->rememberMe) { // However you implement it
    $selector = base64_encode(random_bytes(9));
    $authenticator = random_bytes(33);
    …
}
Álvaro González
  • 142,137
  • 41
  • 261
  • 360