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

如何为Laravel Socialite用户启用双因素认证时禁用Fortify密码确认

方案1:使用Fortify官方提供的密码确认自定义钩子(推荐,侵入性最低)

首先确保你的用户表有可区分第三方登录用户的标识,比如你Socialite登录时写入的provider字段,或者自行新增的is_social_login布尔字段。
在app/Providers/FortifyServiceProvider.php的boot方法中注册自定义密码确认逻辑:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Laravel\Fortify\Fortify;

public function boot()
{
    // 原有Fortify配置保留
    Fortify::confirmPasswordsUsing(function ($user, string $password, Request $request) {
        // 仅在启用双因素认证的请求下,给第三方登录用户跳过密码校验
        if ($request->routeIs('two-factor-authentication.store') && !empty($user->provider)) {
            return true;
        }
        // 普通用户走默认密码校验逻辑
        return Hash::check($password, $user->password);
    });
}

如果你需要所有需要密码确认的场景都给第三方用户跳过,去掉路由判断条件即可。

方案2:覆盖双因素路由,自定义中间件逻辑

如果只需要针对双因素启用场景做特殊处理,不想影响其他密码确认场景,可以直接覆盖Fortify的默认路由,在routes/web.php中添加如下配置:

use Laravel\Fortify\Http\Controllers\TwoFactorAuthenticationController;

// 覆盖Fortify默认的双因素启用路由
Route::post('/user/two-factor-authentication', [TwoFactorAuthenticationController::class, 'store'])
    ->middleware([
        config('fortify.auth_middleware', 'auth').':'.config('fortify.guard'),
        // 自定义密码确认逻辑
        function ($request, $next) {
            $user = $request->user();
            // 非第三方用户才需要走密码确认校验
            if (empty($user->provider)) {
                return app(\Laravel\Fortify\Http\Middleware\RequirePassword::class)->handle($request, $next);
            }
            return $next($request);
        }
    ])->name('two-factor-authentication.store');

配置完成后记得执行php artisan route:cache刷新路由缓存(如果开启了路由缓存)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:54:05