How to test authentication via API with Laravel Passport?

前端 未结 7 1062
轮回少年
轮回少年 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:24

    I think the selected answer is likely the most robust and best here so far, but I wanted to provide an alternative that worked for me if you just need to quickly get tests passing behind passport without a lot of setup.

    Important note: I think if you're going to do a lot of this, this isn't the right way and other answers are better. But in my estimation this does seem to just work

    Here's a full test case where I need to assume a user, POST to an endpoint, and use their Authorization token to make the request.

    create();
            Passport::actingAs($user);
    
            //See Below
            $token = $user->generateToken();
    
            $headers = [ 'Authorization' => 'Bearer $token'];
            $payload = [
                //...
            ];
    
    
    
            $response = $this->json('POST', '/api/resource', $payload, $headers);
    
            $response->assertStatus(200)
                    ->assertJson([
                        //...
                    ]);
    
        }
    }
    

    And for clarity, here is the generateToken() method in the User model, which leverages the HasApiTokens trait.

    public function generateToken() {
        return $this->createToken('my-oauth-client-name')->accessToken; 
    }
    

    This is fairly rough and ready in my opinion. For example it if you're using the RefreshDatabase trait you have to run the passport:install command like this in every method. There may be a better way to do this via global setup, but I'm fairly new to PHPUnit so this is how I'm doing it (for now).

提交回复
热议问题