问题
A user is logged in. And he's also already logged in in 3 different computers. Now user changes his password.
I want to do something to log him out from all of his devices. By default if we change password in one device, nothing happens on other devices.
The first thing that comes in mind is to check password in a middle-ware (every request) which is not good and decreases performance significantly.
How can I do this in Laravel 5?
AND what is the best way to do this? How does big sites logout a user from all devices?
回答1:
In the latest version of Laravel 5.6
You can do this from
auth()->logoutOtherDevices();
logoutOtherDevices
More Info
回答2:
I did something similar. At first I save sessions in Redis. For each login I save session ID after success auth and relate it with user ID (it's array). If user change password you can remove all user sessions except current (using sessions IDs). If user logout you can remove session id from array of user's sessions. (I think you can use MySQL or other storage for saving relation between user and session ID)
for save session ID I use (when user login )
$redis = \LRedis::connection();
$redis->sadd('user:sessions:' . $userId, Session::getId());
for remove sessions ID from array of user sessions (if user logout or manually logout )
$redis->srem('user:sessions:' . $userId, $sessionId);
remove Laravel session (logout user from other device)
$redis->del('laravel:' . $sessionId);
get all session IDs for user
$redis->smembers('user:sessions:' . $userId);
for logout from all devices use loop
$userSessions = $redis->smembers('user:sessions:' . $userId);
$currentSession = Session::getId()
foreach ($userSessions as $sessionId) {
if ($currentSession == $sessionId) {
continue; //if you want don't remove current session
}
$redis->del('laravel:' . $sessionId);
$redis->srem('user:sessions:' . $userId, $sessionId);
}
回答3:
From laravel documents:
Invalidating Sessions On Other Devices
Laravel provides a mechanism for invalidating and "logging out" a user's sessions that are active on other devices without invalidating the session on their current device.
First, you should make sure that the Illuminate\Session\Middleware\AuthenticateSession middleware is present and un-commented in your
app/Http/Kernel.php
class' web middleware group:'web' => [ // ... \Illuminate\Session\Middleware\AuthenticateSession::class, // ... ],
Then, you may use the
logoutOtherDevices
method on the Auth facade. This method requires the user to provide their current password, which your application should accept through an input form:use Illuminate\Support\Facades\Auth; Auth::logoutOtherDevices($password);
When the
logoutOtherDevices
method is invoked, the user's other sessions will be invalidated entirely, meaning they will be "logged out" of all guards they were previously authenticated by.
来源:https://stackoverflow.com/questions/30875866/laravel-5-logout-a-user-from-all-of-his-devices