我实际上是在项目中实现双因素身份验证。我做的是
Auth::user()->google2fa_passed = 1;
事实上,当导航到另一个页面时,它并没有真正存储该值。
我也不想保留在另一个会话中,因为当用户注销(或用户从浏览器中删除会话cookie)时,将显示一个登录页面,并再次进行2因素身份验证。
知道如何在用户会话中再保存一个属性吗?
当您使用Auth::user()
时,它会为您提供身份验证用户的Eloquent模型。
如果要在会话中存储数据,则需要使用Session
facade或session()
helper。
您可以在文档中找到有关会话的更多信息。
PS:旧版本的文档更好(http://laravel.com/docs/5.0/session)。
最终,我使用session
进行存储。
键入6位代码后,将标志存储到会话中
'Session::put('totp_passed', 1);
在app/Http/Middleware/Authenticate.php中,如果会话已过期,则删除2FA会话
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
// remove the 2-factor auth if the user session expired
'Session::forget('totp_passed'); // <------- add this line
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->route('auth.login');
}
}
return $next($request);
}
然后创建另一个中间件,例如app/Http/middleware/TwoFactorAuth.php
namespace App'Http'Middleware;
use Closure;
class TwoFactorAuth
{
/**
* Handle an incoming request.
*
* @param 'Illuminate'Http'Request $request
* @param 'Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (!'Session::has('totp_passed')) {
return redirect()->route('auth.2fa');
}
return $next($request);
}
}
在app/Http/Kernel.php中
protected $routeMiddleware = [
'auth' => 'App'Http'Middleware'Authenticate::class,
'auth.basic' => 'Illuminate'Auth'Middleware'AuthenticateWithBasicAuth::class,
'guest' => 'App'Http'Middleware'RedirectIfAuthenticated::class,
'2fa' => 'App'Http'Middleware'TwoFactorAuth::class, // <------ add this line
];
如何使用
Route::group(['middleware' => 'auth'], function () {
// must be login first only can access this page
Route::get('2fa', ['as' => 'auth.2fa', 'uses' => 'Auth'AuthController@get2FactorAuthentication']);
Route::post('2fa', ['uses' => 'Auth'AuthController@post2FactorAuthentication']);
// add 2-factor auth middleware
Route::group(['middleware' => '2fa'], function () {
// all routes that required login
});
});