You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Fortify中启用LogoutOtherDevices功能

在Laravel Fortify中实现“退出其他设备”功能

Fortify本身没有提供开箱即用的“退出其他设备”功能,但可以借助Laravel核心认证工具快速实现,步骤如下:

1. 添加路由

在routes/web.php中添加POST路由,指定处理逻辑的控制器方法,并添加认证中间件:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::post('/user/logout-other-devices', [UserController::class, 'logoutOtherDevices'])
    ->middleware(['auth'])
    ->name('user.logout.other.devices');

2. 编写控制器逻辑

在UserController中添加处理方法,核心是验证当前用户密码,再调用Laravel自带的logoutOtherDevices方法:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

public function logoutOtherDevices(Request $request)
{
    // 验证密码必填
    $request->validate([
        'password' => 'required|string',
    ]);

    // 校验密码是否匹配当前用户
    if (!Auth::validate(['email' => Auth::user()->email, 'password' => $request->password])) {
        throw ValidationException::withMessages([
            'password' => __('auth.password'),
        ]);
    }

    // 触发退出其他设备逻辑
    Auth::logoutOtherDevices($request->password);

    // 更新当前会话的密码哈希缓存,避免当前会话被意外退出
    $request->session()->put('password_hash_' . Auth::getDefaultDriver(), Auth::user()->getAuthPassword());

    return back()->with('status', '已成功退出其他设备的登录会话');
}

3. 前端表单实现

在用户设置页面添加表单,让用户输入当前密码来触发操作:

<form method="POST" action="{{ route('user.logout.other.devices') }}">
    @csrf

    <div>
        <label for="password">当前登录密码</label>
        <input id="password" type="password" name="password" required autocomplete="current-password">
        @error('password')
            <span class="text-red-500">{{ $message }}</span>
        @enderror
    </div>

    <button type="submit">退出其他设备</button>
</form>

关键说明

  • Auth::logoutOtherDevices()会重新生成用户的remember_token,其他设备的会话因token失效会被强制退出。
  • 密码验证是必要的安全步骤,防止恶意用户利用该功能操作他人账号。
  • 确保用户模型继承自Illuminate\Foundation\Auth\User,该基类已包含所需的认证逻辑和属性。

内容的提问来源于stack exchange,提问作者Umair Saeed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 18:31:45