6

我实际上是在项目中实施 2-factor auth。我所做的是

Auth::user()->google2fa_passed = 1;

实际上它并没有真正存储,当导航到另一个页面时,该值丢失。

我也不想保留另一个会话,因为当用户注销(或用户从浏览器中删除会话 cookie)时,将显示一个登录页面,并再次通过 2 因素身份验证。

知道如何为用户会话再保存 1 个属性吗?

4

2 回答 2

3

当您使用Auth::user()它时,它会为您提供身份验证用户的 Eloquent 模型。

如果要在会话中存储数据,则需要使用Session外观或session()助手。

您可以在文档中找到有关会话的更多信息。

PS:旧版本的文档更好(http://laravel.com/docs/5.0/session)。

于 2015-11-09T09:54:04.863 回答
2

最终,我使用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
    }); 
});
于 2015-11-11T03:39:57.187 回答