Laravel 8升级后功能测试中无法创建Passport Token问题
Laravel 8 Passport Client Credentials 授权返回 invalid_client 问题解决
核心问题分析
你在测试中错误混用了Authorization Code授权流程和Client Credentials授权流程:
- Client Credentials模式不需要经过
passport.authorizations.authorize获取code,也不需要在token请求里传code参数 - 直接创建Client记录时,可能未符合Laravel 8 Passport对Client Credentials类型客户端的字段要求
解决方案步骤
1. 简化测试流程,移除多余授权环节
Client Credentials模式是直接通过客户端ID和秘钥获取token,无需用户授权步骤。修改测试代码如下:
use Illuminate\Support\Str; use Laravel\Passport\Client as OauthClient; use Modules\Sapiendo\Tests\SapiendoTestCase; /** @test */ public function we_can_authenticate_and_use_api_endpoints_with_client_credential_grant_token() { $customer = $this->createFullCustomer(); // 创建Client Credentials类型的客户端 /** @var OauthClient $oauthClient */ $oauthClient = OauthClient::create([ 'user_id' => null, 'name' => 'ClientCredentials Grant Client', 'secret' => Str::random(40), 'redirect' => 'http://localhost', 'personal_access_client' => false, 'password_client' => false, 'revoked' => false, ]); // 直接请求token,无需code参数 $tokenRequest = $this->post(route('passport.token'), [ 'grant_type' => 'client_credentials', 'client_id' => $oauthClient->id, 'client_secret' => $oauthClient->secret, 'scope' => '', // 可根据业务需求设置权限范围 ]); $tokenRequest->assertSuccessful(); dd($tokenRequest->json()); }
2. 用Passport官方方法创建客户端(更可靠)
直接调用Passport提供的方法创建客户端,避免手动设置字段时遗漏要求:
// 使用Passport内置方法创建Client Credentials客户端 $oauthClient = \Laravel\Passport\Client::createClient( null, 'ClientCredentials Grant Client', 'http://localhost', false, // 非personal access client false // 非password client );
3. 检查Passport配置与迁移
升级到Laravel 8后,确保完成Passport最新迁移:
php artisan migrate
同时确认config/passport.php中启用了Client Credentials授权:
// config/passport.php 'grant_types' => [ 'authorization_code' => true, 'password' => true, 'client_credentials' => true, // 确保此选项为true 'refresh_token' => true, ],
4. 验证请求参数准确性
- 确认
client_id为客户端的id字段值,而非其他标识 - 确认
client_secret与创建时设置的secret值完全一致,注意大小写和无多余空格 - 彻底移除请求中的
code参数,Client Credentials模式不依赖该参数
内容的提问来源于stack exchange,提问作者dolor3sh4ze
相关产品推荐
相关产品推荐

