How to enable an MFA "Trusted Device" in Laravel Project so user not prompted every time?

69 Views Asked by At

I have successfully implemented SMS based MFA on a Laravel project following the guide here: https://www.nicesnippets.com/blog/laravel-10-two-factor-authentication-with-sms-example and AWS for SMS messaging. This works really well but unfortunately I cannot work out how to use cookies allow a user to 'trust' a device and avoid the need for MFA on every login.

The tutorial relies on the following Middleware added to the project:

class TwoFactorAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next){
        Log::info('TwoFactorAuth middleware triggered');
        if (!Session::has('user_2fa')) {
            return redirect()->route('2fa.index');
        }
        return $next($request);
    }
}

And the following simple model:

class UserCode extends Model{
    use HasFactory;
    public $table = "user_codes";
    protected $fillable = [
        'user_id',
        'code',
    ];
}

The app/Http/Kernel.php is updated to activate the middleware:

class Kernel extends HttpKernel
{
    protected $routeMiddleware = [
        ....
        '2fa' => \App\Http\Middleware\TwoFactorAuth::class,
    ];
}

I have tried using a cookie called 'trust-device' which gets created when the user logs in (if they have checked the "Trust Device" box on the login page. The cookie gets created but now I don't know where to implement the code to look for that and circumvent the MFA requirement. I tried adding the following to the authenticated function within the standard Laravel LoginController.php page:

    protected function authenticated(\Illuminate\Http\Request $request, $user){
        Log::info('Login controller "authenticated" triggered');
        if(request()->cookie('trust_device')=='true') {
            Log::info('Found trust_device cookie so creating user_2fa and tfa session');
            \Session::put('user_2fa', auth()->user()->id);
            \Session::put('tfa', auth()->user()->id);
        }

But the user is still prompted for MFA everytime.

0

There are 0 best solutions below