5

I'm trying to test an authenticated API route which only an authenticated user can post to a specific route.

Looking at the Laravel Sanctum docs, I can use the code below to create and authenticate a user:

Sanctum::actingAs(
    factory(User::class)->create(),
    ['*']
);

When I try replicate this, I get an error running the test

BadMethodCallException: Call to undefined method App\User::withAccessToken()

My test code is as follows:

    public function an_authenticated_user_can_add_a_client()
    {
        $user = Sanctum::actingAs(
            factory(User::class)->create(),
            ['*']
        );
        dd($user);
        // $this->post('/api/clients', $this->data());
    }

api.php

Route::middleware('auth:sanctum')->group(function () {

    //Clients
    Route::get('/clients/{client}','ContactsController@show');
    Route::post('/clients','ContactsController@store');
    Route::patch('/clients/{client}','ContactsController@update');
    Route::delete('/clients/{client}','ContactsController@destroy');
});

I don't have the method withAccessToken() in my User class and can't see where this method is coming from or specified anywhere. Any help would be greatly appreciated.

mrhn
  • 17,961
  • 4
  • 27
  • 46
basic
  • 219
  • 6
  • 12

2 Answers2

5

Laravel Sanctum for SPA uses normal session authentication so the default actingAs method works fine. The actingAs method in Sanctum is meant to use for api tokens. Hope it helps.

4

Your User model is missing the HasApiTokens trait, that gives the function you are missing to the User model. Also described in the documentation, under the section Issuing API Tokens.

use Laravel\Sanctum\HasApiTokens;

class User {
    use HasApiTokens;
}
mrhn
  • 17,961
  • 4
  • 27
  • 46
  • 1
    I see, that worked perfectly, thank you. Although I notice that inside the documentation, it mentions that API tokens should not be used on a first-party SPA (which I'm building an SPA), excuse my lack of experience, would I want to issue an API token in my case of testing to see if an authenticated user can add to the database? As I understand, SPA authentication is just grabbing a csrf-cookie instead of a token? – basic Apr 11 '20 at 02:15
  • See Javier's answer if you are using SPA Authentication – PW_Parsons May 06 '20 at 19:25
  • @basic if you're using SPA, don't issue token as simply using session and cookie is just enough. Sanctum tries all form of auth before yielding to token based authentication. this means if a user sends a request to a sanctum auth url and the user has web auth, it will go through with user have all privilege set to '*' – Stanley Aloh Dec 31 '22 at 09:58