You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 03:40:48