@arifkhn46 Have the same issue, did you find a way without commenting out the code or ?
Sanctum: Issue with user logout case + TDD
Description:
I am writing a use case to logout a user, so on Logout request, I delete all the user tokens so that every token issued previously becomes invalid for further requests.
Following is the feature test case:
/** @test */
public function a_user_can_logout()
{
// $this->withoutExceptionHandling();
$this->jsonPost(route('api.user.logout'))->assertStatus(401);
$user = factory('App\User')->create();
$response = $this->json('POST', route('api.user.login'), [
'email'=> $user->email,
'password' => 'password'
])->assertStatus(200);
$this->jsonPost(route('api.user.logout'), [], $response->json()['access_token'])->assertStatus(200);
$this->jsonPost(route('api.user.profile'), [], $response->json()['access_token'])->assertStatus(401);
}
Now on logout request following method runs:
public function logout()
{
auth()->user()->tokens()->delete();
return response()->json(['message' => 'Successfully logged out']);
}
Now comes the bug part, in the last assertion i.e. $this->jsonPost(route('api.user.profile'), [], $response->json()['access_token'])->assertStatus(401); I am calling user profile API which should return the status as 401 but it always returns 200.

My profit method:
public function profile()
{
return response()->json(auth()->user());
}
I tried to debug the issue and the following are my observations:
-
I am facing this issue when I run this feature test through the command line. If I test the same thing on POSTMAN Client the functionality is just working fine. So this issue is related to TDD.
-
There is a method in the class Illuminate/Auth/RequestGuard.php
public function user()
{
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
return $this->user = call_user_func(
$this->callback, $this->request, $this->getProvider()
);
}
In this method Laravel is caching user object for performance optimization. And If we comment out the caching code i.e.
if (! is_null($this->user)) {
return $this->user;
}
my feature test case runs perfectly.

Following is my route list:

Steps To Reproduce:
- Setup Laravel 7 and Sanctum
- Setup API routes for login, log out, and user profile or any sanctum token protected route.
- Create a feature test or use the above feature test code.
- Run the tests.
Please or to participate in this conversation.