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

Laravel Passport 11.8报unsupported_grant_type错误求助

Laravel 10 + Passport 11.8 解决 unsupported_grant_type 错误

可能的原因及解决办法

1. 请求未携带正确参数(核心问题)

你的控制器代码中,创建新请求时未传递添加的参数。$request->create() 方法的第三个参数是请求的表单/查询参数,当前仅指定了URL和请求方法,导致 /oauth/token 接口未收到 grant_type 等关键参数,从而触发报错。

修改控制器代码:

public function getTokenAndRefreshToken($request, $client)
{
    $postData = [
       'grant_type' => 'password',
       'client_id' => $client->id,
       'client_secret' => $client->secret,
       'username' => $request->email,
       'password' => $request->password,
       'scope' => '*',
    ];

    $instance = Route::dispatch(
        $request->create(
           '/oauth/token', 
           'post',
           $postData // 传递参数数组
        )
    );

    return json_decode($instance->getContent());
}

2. 客户端类型错误或未启用密码授权模式

密码授权模式需要对应类型的客户端支持,确保你创建的是密码授权客户端,而非个人访问客户端或授权码客户端。

运行以下命令创建密码授权客户端:

php artisan passport:client --password

执行时按提示输入客户端名称(可直接回车),无需填写回调URL。创建完成后记录生成的 client_id 和 client_secret,确保代码中使用的是这组值。

3. 请求Content-Type不符合要求

/oauth/token 接口要求请求内容类型为 application/x-www-form-urlencoded,若通过Postman等工具测试,需选择 form-data 或 x-www-form-urlencoded 格式,而非raw JSON。

若需在代码中强制设置请求头,可修改 $request->create 方法:

$instance = Route::dispatch(
    $request->create(
       '/oauth/token', 
       'post',
       $postData,
       [], // cookies
       [], // files
       [
           'CONTENT_TYPE' => 'application/x-www-form-urlencoded',
           'HTTP_ACCEPT' => 'application/json',
       ]
    )
);

4. 未正确加载Passport路由

确保在 routes/api.php 中注册Passport路由:

// 注册全部Passport路由
Passport::routes();

// 或仅注册密码授权相关路由(精简版)
Passport::routes(function ($router) {
    $router->forAccessTokens();
});

5. 配置缓存导致配置未生效

若修改过 config/auth.php 等配置文件,需清除配置缓存:

php artisan config:clear

内容的提问来源于stack exchange,提问作者Shekh Saifuddin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:15:18