我正在使用 google2fa-laravel 包为我的用户在注册和登录时启用 OTP 验证。该文档描述了如何在注册路径中为用户注册 2fa 密钥,但是它没有很好地描述如何为用户启用登录验证。
我知道有一个
2fa
中间件路由 可以添加它来将用户推送到 google2fa.php
配置文件中设置的特定视图,但仅此而已。
我创建了自己的视图,对应于
google2fa.php
,如下所示:
'view' => 'auth.otp'
我的auth/otop.blade.php
<form class="form-horizontal" method="POST" action="{{ route('verify') }}">
{{ csrf_field() }}
<div class="form-group">
<p>Please enter the one time password generated on your Google Authenticator App. <br> Ensure you submit the current one because it refreshes every 30 seconds.</p>
<label for="one_time_password" class="col-md-4 control-label">One Time Password</label>
<input id="one_time_password" type="number" class="form-control col-md-6" name="one_time_password" required autofocus>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">Verify</button>
</div>
</div>
</form>
你可以看到我在我的路径中指向了一条名为
verify
的路线,但这实际上不会通往任何地方,文档指向 /google2fa/authenticate
但这条路线不是由包定义的,也没有在任何地方提到否则什么都不做并导致 404。
我创建了一条名为
verify
的路线,它运行一个运行以下命令的方法:
public function verifySession(Request $request)
{
$google2fa = app('pragmarx.google2fa');
$secret = $request->input('one_time_password');
$valid = $google2fa->verifyKey(auth()->user()->google2fa_secret, $secret);
Log::debug($valid);
}
我获得了有关如何使用源包 google2fa 验证密钥的信息,而我的代码验证了代码,如果我返回到最初使用
2fa
单击的路线,我不确定下一步该做什么
中间件,它没有注册我已验证自己并再次将我重定向到 OTP 页面。
希望获得一些有关如何解决此问题的指导。
我做了类似的事情,如果 $valid,它基本上只是重定向到主页(已登录),如果不是,它将返回原始索引视图以重新输入 otp(假设他们以某种方式输入错误)。希望这有帮助!
$valid = $google2fa->verifyKey($request->google2fa_secret, $request->one_time_password);
if ($valid) {
$request->session()->put('login', 1);
return redirect(route('home'));
} else {
return view('google2fa.index', ['show_QR' => false, 'QR_Image' => '', 'secret' => '');
}
验证成功后,您需要将用户登录到Google2FA会话中。
public function verify(Request $request)
{
$request->validate([
'otp' => 'required|numeric',
]);
if (!Google2FA::verifyKey(Auth::user()->google2fa_secret, $request->otp)) {
return back()->withErrors('Invalid One Time Password');
}
Google2FA::login();
return redirect('/home');
}
因此,您还需要在用户注销您的应用程序后将用户注销。
Google2FA::logout();