Laravel 8 Fortify - 仅当用户从新设备登录时才 2FA

问题描述

我正在 Laravel 8 应用程序中实施两步验证 (2FA)。

每次用户登录时都会应用2FA。但是,我真的不觉得每次都需要2FA,我什至觉得很烦人。作为一种解决方案,我正在考虑仅在用户从新设备连接时应用它。是否有人已经这样做了,或者谁能给我一些必要的更改提示

解决方法

根据这一行:https://github.com/laravel/fortify/blob/82c99b6999f7e89f402cfd7eb4074e619382b3b7/src/Http/Controllers/AuthenticatedSessionController.php#L80

您可以在强化配置文件中创建一个 pipelines.login 条目。

解决方案是:

  • 创建配置条目
  • 复制上述文件第 84 行中的管道设置。
  • 创建自定义 AttemptToAuthenticate 类,确保管道配置指向您的新类。
  • 使新类扩展默认的强化 AttemptToAuthenticate 类。
  • 覆盖 handle 函数,在新函数中添加您的逻辑,您可以在其中检查设备上的 cookie。
,

我知道了。以下是我遵循的步骤:

  1. 在配置文件 fortify.php 中我添加了

    'pipelines' => [
        'login' => [
            App\Actions\Fortify\RedirectIfTwoFactorAuthenticatable::class,Laravel\Fortify\Actions\AttemptToAuthenticate::class,Laravel\Fortify\Actions\PrepareAuthenticatedSession::class,]
    ]
    
  2. 我已将字段 two_factor_cookies 添加到 User 类。

  3. 我已经自定义了 RedirectIfTwoFactorAuthenticatable 类 强化:

    <?php
    
    namespace App\Actions\Fortify;
    
    use Laravel\Fortify\Actions\RedirectIfTwoFactorAuthenticatable as DefaultRedirectIfTwoFactorAuthenticatable;
    use Laravel\Fortify\TwoFactorAuthenticatable;
    
    
    class RedirectIfTwoFactorAuthenticatable extends DefaultRedirectIfTwoFactorAuthenticatable
    {
    
        /**
         * Handle the incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  callable  $next
         * @return mixed
         */
        public function handle($request,$next)
        {
            $user = $this->validateCredentials($request);
    
            if (optional($user)->two_factor_secret &&
                in_array(TwoFactorAuthenticatable::class,class_uses_recursive($user)) &&
                $this->checkIfUserDeviceHasNotCookie($user)) {
                return $this->twoFactorChallengeResponse($request,$user);
            }
    
            return $next($request);
        }
    
        /**
         * This checks if the user's device has the cookie stored 
         * in the database.
         *
         * @param  \App\Models\User\User  $user
         * @return bool
         */
        protected function checkIfUserDeviceHasNotCookie($user)
        {
            $two_factor_cookies = json_decode($user->two_factor_cookies);
            if (!is_array($two_factor_cookies)){
                $two_factor_cookies = [];
            }
            $two_factor_cookie = \Cookie::get('2fa');
            return !in_array($two_factor_cookie,$two_factor_cookies);
        }
    
    }
    
  4. 在 FortifyServiceProvider 中,我添加了一个自定义的 TwoFactorLoginResponse。

        <?php
    
        namespace App\Providers;
    
        use App\Actions\Fortify\CreateNewUser;
        use App\Actions\Fortify\ResetUserPassword;
        use App\Actions\Fortify\UpdateUserPassword;
        use App\Actions\Fortify\UpdateUserProfileInformation;
        use App\Http\Responses\FailedPasswordResetLinkRequestResponse;
        use App\Http\Responses\FailedPasswordResetResponse;
        use App\Http\Responses\LockoutResponse;
        use App\Http\Responses\LoginResponse;
        use App\Http\Responses\LogoutResponse;
        use App\Http\Responses\PasswordResetResponse;
        use App\Http\Responses\RegisterResponse;
        use App\Http\Responses\SuccessfulPasswordResetLinkRequestResponse;
        use App\Http\Responses\TwoFactorLoginResponse;
        use App\Http\Responses\VerifyEmail;
        use Illuminate\Cache\RateLimiting\Limit;
        use Illuminate\Http\Request;
        use Illuminate\Support\Facades\RateLimiter;
        use Illuminate\Support\ServiceProvider;
        use Laravel\Fortify\Contracts\FailedPasswordResetLinkRequestResponse as FailedPasswordResetLinkRequestResponseContract;
        use Laravel\Fortify\Contracts\FailedPasswordResetResponse as FailedPasswordResetResponseContract;
        use Laravel\Fortify\Contracts\LockoutResponse as LockoutResponseContract;
        use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
        use Laravel\Fortify\Contracts\LogoutResponse as LogoutResponseContract;
        use Laravel\Fortify\Contracts\PasswordResetResponse as PasswordResetResponseContract;
        use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
        use Laravel\Fortify\Contracts\SuccessfulPasswordResetLinkRequestResponse as SuccessfulPasswordResetLinkRequestResponseContract;
        use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
        use Laravel\Fortify\Fortify;
    
        class FortifyServiceProvider extends ServiceProvider
        {
            /**
             * Register any application services.
             *
             * @return void
             */
            public function register()
            {
                $this->registerResponseBindings();
            }
    
            /**
             * Register the response bindings.
             *
             * @return void
             */
            protected function registerResponseBindings()
            {
                $this->app->singleton(LoginResponseContract::class,LoginResponse::class);
                $this->app->singleton(LogoutResponseContract::class,LogoutResponse::class);
                $this->app->singleton(TwoFactorLoginResponseContract::class,TwoFactorLoginResponse::class);
                $this->app->singleton(RegisterResponseContract::class,RegisterResponse::class);
    
                $this->app->singleton(LockoutResponseContract::class,LockoutResponse::class);
                $this->app->singleton(SuccessfulPasswordResetLinkRequestResponseContract::class,SuccessfulPasswordResetLinkRequestResponse::class);
                $this->app->singleton(FailedPasswordResetLinkRequestResponseContract::class,FailedPasswordResetLinkRequestResponse::class);
                $this->app->singleton(PasswordResetResponseContract::class,PasswordResetResponse::class);
                $this->app->singleton(FailedPasswordResetResponseContract::class,FailedPasswordResetResponse::class);        
            }
    
            /**
             * Bootstrap any application services.
             *
             * @return void
             */
            public function boot()
            {
    
                Fortify::ignoreRoutes();
                Fortify::loginView(function () {
                    return view('auth.login');
                });
                Fortify::twoFactorChallengeView('auth.two-factor-challenge');
                Fortify::confirmPasswordView(function (Request $request) {
                    if ($request->ajax()) {
                        return view('auth.confirm-password-form');
                    } else {
                        return view('auth.confirm-password');
                    }
                });
    
                Fortify::requestPasswordResetLinkView(function () {
                    return view('auth.forgot-password');
                });
                Fortify::resetPasswordView(function ($request) {
                    return view('auth.reset-password',['request' => $request,'token' => $request->route('token')]);
                });
                Fortify::registerView(function () {
                    return view('auth.register'); 
                });
                Fortify::verifyEmailView(function () {
                    return view('auth.verify');
                });
    
                Fortify::createUsersUsing(CreateNewUser::class);
                Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
                Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);
                Fortify::resetUserPasswordsUsing(ResetUserPassword::class);
    
                /*RateLimiter::for('login',function (Request $request) {
                    return Limit::perMinute(5)->by($request->email.$request->ip());
                });*/
    
                RateLimiter::for('two-factor',function (Request $request) {
                    return Limit::perMinute(5)->by($request->session()->get('login.id'));
                });
            }
        }
    
  5. 最后,TwoFactorLoginResponse:

    <?php
    
    namespace App\Http\Responses;
    
    use Illuminate\Http\JsonResponse;
    use Laravel\Fortify\Contracts\TwoFactorLoginResponse as TwoFactorLoginResponseContract;
    
    class TwoFactorLoginResponse implements TwoFactorLoginResponseContract
    {
        /**
         * Create an HTTP response that represents the object.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Symfony\Component\HttpFoundation\Response
         */
        public function toResponse($request)
        {
            $user = \Auth::user();
    
            $this->storeCookieIfNotInDB($user);
    
            $role = $user->role;
    
            if ($request->wantsJson()) {
                return new JsonResponse('',204);
            }
    
            if ($role == "0") {
                return redirect()->route('user.home');
            } else {
                return redirect()->route('admin.home');
            }
        }
    
        /**
         * Store the cookie if it is not in the database.
         *
         * @param  \App\Models\User\User  $user
         * @return void
         */
        protected function storeCookieIfNotInDB($user)
        {
            $two_factor_cookies = json_decode($user->two_factor_cookies);
            if (!is_array($two_factor_cookies)){
                $two_factor_cookies = [];
            }
            $two_factor_cookie = \Cookie::get('2fa');
    
            if (!in_array($two_factor_cookie,$two_factor_cookies)) {
                $two_factor_cookie = md5(now());
                $two_factor_cookies[] = $two_factor_cookie;
                if (count($two_factor_cookies) > 3) {
                    array_shift($two_factor_cookies);
                }
    
                $user->two_factor_cookies = json_encode($two_factor_cookies);
                $user->save();
    
                $lifetime = 60 * 24 * 365; //one year
                \Cookie::queue('2fa',$two_factor_cookie,$lifetime);
            }
        }
    }
    

登录后,它将查找 cookie 2fa。如果其内容存储在数据库中,则无需再次输入代码。为了防止在数据库中保存无限的 cookie 内容,您可以添加一个最大限制(我已将其设置为 3)。

感谢 Maarten Veerman 的初步帮助。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...