Framework: BUG: actingAs() not working for POST requests

Created on 7 Oct 2017  Â·  6Comments  Â·  Source: laravel/framework

  • Laravel Version: 5.5.14
  • PHP Version: 7.1
  • Database Driver & Version: MySQL Homestead Latest

Description:

When using phpunit testing, actingAs() is not authenticating POST requests. I am using Laravel Passport so it could be a factor.

Steps To Reproduce:

  1. Create a POST route that requires authentication (auth:api middleware).
  2. Create a new Test to create a user, authenticate as them and submit a POST request to route.

Expected Output

Authenticated request and action taken (my example was a create)

Actual Output

Unauthenticated JSON response from the endpoint. (used dump() to find out).

Test Code

````php
public function testSuperAdminsCanCreateATeam()
{
$faker = app(Generator::class);
$data = [
'name' => $faker->word,
'company' => $faker->company,
'address' => $faker->address,
'telephone' => $faker->phoneNumber,
'email' => $faker->unique()->safeEmail,
'vat_number' => 0
];
$user = factory(User::class)->create(['super_admin' => true]);

    $response = $this
        ->actingAs($user)
        ->json('POST', route('api.teams.store'), $data);

    $response
        ->dump()     // Dump here shows Unauthenticated response.
        ->assertStatus(Response::HTTP_CREATED)
        ->assertJson([
            'status' => 'success',
            'data' => array_merge(
                ['owner_id' => $user->id],
                $data
            )
        ]);
}

````

Most helpful comment

@Jamesking56 try actingAs($user, 'api')

All 6 comments

Can you try it out with simpler example? I have tried actingAs (not this example that you have provided) and it works fine. I think the bug could be with how you are assigning roles or doing some authorisation check we don't know about

I'm using the default Passport guard, I don't have any custom authentication.

I'm also using the default auth:api middleware.

It could be a bug in Passport rather than Laravel itself, I'm not sure

On Sat, Oct 7, 2017 at 7:13 PM +0100, "Dylan DPC" notifications@github.com wrote:

Can you try it out with simpler example? I have tried actingAs (not this example that you have provided) and it works fine. I think the bug could be with how you are assigning roles or doing some authorisation check we don't know about

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub, or mute the thread.

@Jamesking56 try actingAs($user, 'api')

Can confirm that using Passport::actingAs($user) works.

@Jamesking56 try actingAs($user, 'api')

this works for me

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ThomHurks picture ThomHurks  Â·  75Comments

itsgoingd picture itsgoingd  Â·  81Comments

mianshargeel picture mianshargeel  Â·  59Comments

JosephSilber picture JosephSilber  Â·  176Comments

mrahmadt picture mrahmadt  Â·  61Comments