所以继续我上面的评论 - 这是我尝试过的并且没有任何故障的工作:
配置/auth.php
'guards' => [
//..
'agent' => [
'driver' => 'session',
'provider' => 'users',
],
//...
],
应用程序/Http/Controllers/HomeController.php
public function index(): JsonResponse
{
return new JsonResponse([
'user' => auth()->guard('agent')->user(),
]);
}
路线/web.php
Route::get('/', 'HomeController@index')->name('home');
测试/功能/HomeTest.php
/**
* @test
*/
public function returns_user()
{
$this->actingAs($user = factory(User::class)->create(), 'agent');
$this->assertTrue($user->exists);
$this->assertAuthenticatedAs($user, 'agent');
$response = $this->get(route('home'));
$response->assertExactJson([
'user_id' => $user->toArray()
]);
}
/**
* @test
*/
public function does_not_return_user_for_non_agent_guard()
{
$this->actingAs($user = factory(User::class)->create(), 'web');
$this->assertTrue($user->exists);
$this->assertAuthenticatedAs($user, 'web');
$response = $this->get(route('home'));
$response->assertExactJson([
'user_id' => null
]);
}
并且测试通过得很好,所以我只能猜测你的agent
守卫或auth:agent
中间件的实现有什么问题。