当使用用户 ID 而不是账号密码登录系统时,如何退出其它设备的登录状态?

背景:

从5.6开始提供了logoutOtherDevices()来清除当前用户的其他会话,原理是通过对密码进行重新Hash::make后对比password_hash(会写入数据库,看updated_at字段就知道。),清除session_attributes中password_hash与本次密码Hash不同的Session。

问题:

当直接使用Auth::loginUsingId(1, $remember = false);登录系统时,可没有密码用于Hash,那么如何清除本用户在其它设备的登录状态?(或者说如何找出本用户的SessionID?正在试验中……)

方法:

Auth::loginUsingId(1, $remember = false);       //登录指定用户 ID 的用户到应用上
<?php

namespace Illuminate\Auth;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Contracts\Auth\SupportsBasicAuth;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Cookie\QueueingFactory as CookieJar;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use RuntimeException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class SessionGuard implements StatefulGuard, SupportsBasicAuth
{

……

    /**
     * Invalidate other sessions for the current user.
     *
     * The application must be using the AuthenticateSession middleware.
     *
     * @param  string  $password
     * @param  string  $attribute
     * @return bool|null
     */
    public function logoutOtherDevices($password, $attribute = 'password')
    {
        if (! $this->user()) {
            return;
        }
        $result = tap($this->user()->forceFill([
            $attribute => Hash::make($password),
        ]))->save();
        if ($this->recaller() ||
            $this->getCookieJar()->hasQueued($this->getRecallerName())) {
            $this->queueRecallerCookie($this->user());
        }
        $this->fireOtherDeviceLogoutEvent($this->user());
        return $result;
    }

……

}
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

博客:一个中间件加几行代码搞定 SSO 单点登录
放弃logoutOtherDevices,改用中间件来实现。

4年前 评论
friendOfTime 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!