Laravel [5.2.21]自定义Auth Guard不会持续存在

时间:2016-02-26 21:00:55

标签: php laravel authentication laravel-5

我正在尝试设置一个自定义的auth警卫,一切都在工作。我可以记录Model,但是一旦我将访问者重定向到新页面,身份验证就会丢失。在控制器执行重定向之前,我可以dd()Auth::guard('client')->user()就好了,但在null中间件中出现AuthenticateClient

我正在使用默认防护来验证用户,一切都正常。我确保这些路由位于启用会话的web中间件下。

我搜索过类似的问题,但我无法找到有效的解决方案。任何想法如何解决这个问题?

旁注:我知道我在下面的代码示例中使用token,但我做的不仅仅是验证该令牌。所以这是一个与为api验证令牌不同的系统。

路线:

Route::group(['middleware' => 'web'], function () {
    // other routes...

    Route::get('client/login/{token}', ['as' => 'client.token', 'uses' => 'Auth\ClientController@attemptTokenLogin']);

    Route::group(['prefix' => 'client', 'middleware' => 'auth.client'], function () {
       Route::get('dashboard', ['as' => 'client.dashboard',  'uses' => 'ClientController@dashboard']);
    });
});

auth.php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        // new auth guard
        'client' => [
            'driver' => 'session',
            'provider' => 'clients',
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],

        // new guard provider
        'clients' => [
            'driver' => 'eloquent',
            'model' => App\Client::class,
        ],
    ],
];

HTTP / Kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    // new...
    'auth.client' => \App\Http\Middleware\AuthenticateClient::class,
];

ClientController @ attemptTokenLogin

$client = // get the client in a custom way...
Auth::guard('client')->login($client);

// dd(Auth::guard('client')->user()); // this works here

return redirect()->route('client.dashboard');

AuthenticateClient

public function handle($request, Closure $next)
{
    // dd(Auth::guard('client')->user()); // this does not work here

    if (!Auth::guard('client')->check()) {
        return redirect()->route('client.login');
    }

    return $next($request);
}

1 个答案:

答案 0 :(得分:4)

实施Illuminate\Contracts\Auth\Authenticatable时,我没有回复getAuthIdentifierName()getAuthIdentifier()

所以...

public function getAuthIdentifierName()
{
    $this->getKeyName();
}

public function getAuthIdentifier()
{
    $this->getKey();
}

应该是......

public function getAuthIdentifierName()
{
    return $this->getKeyName();
}

public function getAuthIdentifier()
{
    return $this->getKey();
}