dimanche 21 octobre 2018

Issue with Laravel Passport when testing my api

I am trying to test multiauth via laravel passport and i am facing a problem sending the authorization token

basically I have two auth guards

'guards' => [
    'api' => [
        'driver' => 'passport',
        'provider' => 'users',
    ],

    'admin' => [
        'driver' => 'passport',
        'provider' => 'admins',
    ],
],

two routes that require different authentication

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::middleware('auth:admin')->get('/admin', function (Request $request) {
    return $request->user();
});

and a test

/** @test */
public function user_can_register()
{
    (new ClientRepository)->createPasswordGrantClient(
        null, 'Laravel Personal Access Client', 'http://localhost'
    );

    factory(Admin::class)->create(['email' => 'john.doe@example.com', 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm']);

    $response = $this->postJson('/api/register', [
        'name' => 'john doe',
        'email' => 'john.doe@example.com',
        'password' => 'secret',
        'password_confirmation' => 'secret'
    ]);

    $response->assertStatus(200);
    $json = $response->json();
    $this->assertEquals('Bearer',$json['token_type']);
    $this->assertNotNull($json['expires_in']);
    $this->assertNotNull($json['access_token']);
    $this->assertNotNull($json['refresh_token']);

    $this->getJson('/api/user',[
        'Authorization' => 'Bearer '.$json['access_token']
    ])->assertStatus(Response::HTTP_OK);

    $this->getJson('/api/admin',[
        'Authorization' => 'Bearer '.$json['access_token']
    ])->assertStatus(Response::HTTP_UNAUTHORIZED);
}

the strange behavior is that test is failing to assert that the call to /api/admin is returning 401. it says that is returning 200 instead. BUT i am testing the same thing via postman and everything is okey. I think that the way i am sending the Authorization header is not appropriate but could not find a better way. Any idea?

Aucun commentaire:

Enregistrer un commentaire