'Laravel Cookie::forget() does not expire cookie
I have this block that sets cookies:
$unique_session_token = bin2hex(random_bytes(24));
$current_session = $request->cookie('session',null);
if ($current_session) {
return 'Already authenticated';
}
if ($is_key_valid === true) { // respond with new cookie containing session token
$response = new Response("Authenticated");
$response->withCookie('session', $unique_session_token, 15);
// add cookie to cache
Cache::put('token:' . $unique_session_token, true, 900); // add cookie to cache
// update session token in db
DB::table('users')
->where('name', '=', $user_query)
->update(['session_token' => $unique_session_token]);
return $response;
} else {
return 'Authentication failed';
}
That sets the cookie and stores it in a Redis cache.
On a logout function, it should expire the cookie here:
$current_session = Cookie::get('session');
if (Cache::has('token:' . $current_session)) { // if token exists
Cache::pull('token:' . $current_session); // destroy token
Cookie::forget('session');
DB::table('users')
->where('session_token', '=', $current_session)
->update(['session_token' => null]);
return 'Logged out';
} else {
return 'Not logged in';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|