How to test authentication via API with Laravel Passport?

前端 未结 7 1064
轮回少年
轮回少年 2020-12-24 07:55

I\'m trying to test the authentication with Laravel\'s Passport and there\'s no way... always received a 401 of that client is invalid, I\'ll leave you what I\'ve tried:

相关标签:
7条回答
  • 2020-12-24 08:29

    Testing Personal Access Tokens

    Here is an example for any who are looking to test your api using personal access tokens.

    First, set up the test class

    protected function setUp(): void
    {
        parent::setUp();
        $this->actingAs(User::first());
        $this->access_token = $this->getAccessToken();
    }
    

    As for the getAccessToken() method, just use the Passport frontend api

    private function getAccessToken()
    {
        $response = $this->post('/oauth/personal-access-tokens',[
            'name' => 'temp-test-token'
        ]);
    
        return $response->json('accessToken');
    }
    

    And simply:

    public function the_personal_access_token_allows_us_to_use_the_api()
    {
        $response = $this->get('/api/user', [
            'Authorization' => "Bearer $this->access_token"
        ]);
    
    
        $response->assertStatus(200);
    
    }
    
    0 讨论(0)
提交回复
热议问题