我正在尝试设置自定义身份验证保护,一切正常。我能够登录 Model
,但是一旦我将访问者重定向到新页面,身份验证就会丢失。我可以在 Controller 执行重定向之前 dd() Auth::guard('client')->user()
就好了,但是在AuthenticateClient
中间件。
我正在使用默认的保护程序来验证用户,并且一切正常。我已确保路由位于启用 session 的 web
中间件下。
我搜索过类似的问题,但找不到有效的解决方案。有什么解决办法吗?
旁注:我知道我在下面的代码示例中使用了 token
,但我所做的不仅仅是针对该 token 进行验证。所以这是一个不同于为 api 验证 token 的系统。
路线:
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);
}
最佳答案
在实现 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();
}
关于php - Laravel [5.2.21] 自定义 Auth Guard 不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35661670/