Summer Sale! All accounts are 50% off this week.

ivymasterman's avatar

Tests with Sanctum 'ActingAs' method fails to work, with status code 403

Here is my test function:

public function test_api_logout_accessible_by_authorized_user()
    {
        Sanctum::actingAs(
            User::factory()->create(),
            ['*']
        );
     
        $response = $this->postJson('/api/logout');

        $response->assertStatus(200);
    }

The Sanctum facade seems to work partially, since it does not return the 401 status, but rather 403.

Expected response status code [200] but received 403.
  Failed asserting that 200 is identical to 403.

Here is the controller endpoint code:

public function logout()
    {
        Auth::user()->currentAccessToken()->delete();
        Auth::user()->dms_tokens()->delete();

        return response()->json([
            "data" => [],
            "message" => "Successfully logged out!"
        ], 200);
    }
0 likes
3 replies
aidil's avatar
aidil
Best Answer
Level 1

One potential cause of this issue could be that the user that is being passed to the actingAs method in the test function is not properly authenticated. Make sure that the user object being passed to the actingAs method is a valid user object that has been properly saved to the database.

Another possible cause of this issue could be that the Auth::user() method is returning a null object, this could happen if you don't have session enabled on the api routes, to enable this you need to specify auth:sanctum on the api guard in config/auth.php.

It's also a good idea to check the user's roles and permissions to ensure that the user has the necessary permissions to access the logout endpoint.

You may also have issue on the endpoint side, make sure the you don't have any middleware restriction that preventing the access to the logout.

Lastly, you can debug by adding a dd(Auth::user()) on the logout controller, this would give you better insight of what's happening on the controller level.

1 like
ivymasterman's avatar

It was an issue with the roles! Forgot to add them to the newly created user.

Please or to participate in this conversation.