Laravel 5: 如何将额外的属性存储到用户登录会话

Laravel 5: How to store extra attributes to user login session

我实际上在项目中实施了 2 因素身份验证。我所做的是

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

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

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

知道如何将另外 1 个属性保存到用户会话吗?

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

如果你想在会话中存储数据,你需要使用 Session facade 或 session() helper。

您可以找到有关会话 in the documentation 的更多信息。

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

最后,我用session来存储。

输入6位密码后,将flag存入session

\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
    }); 
});