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

Laravel Passport自定义OAuth2授权类型遇unsupported_grant_type错误

解决Laravel Passport自定义Mobile授权类型的unsupported_grant_type错误

你遇到的错误核心是授权服务器未正确识别mobile自定义授权类型,以下是针对性的排查和解决步骤:

1. 使用Passport官方扩展方式注册授权类型

直接操作AuthorizationServer实例的方式可能被Passport内部初始化流程覆盖,正确做法是用Passport的extend方法注册:

修改AppServiceProvider的boot方法:

use Laravel\Passport\Passport;
use App\Grants\MobileGrant;

public function boot(): void
{
    Passport::extend('mobile', function ($app) {
        return new MobileGrant(
            $app->make(\Laravel\Passport\Bridge\UserRepository::class),
            $app->make(\Laravel\Passport\Bridge\RefreshTokenRepository::class)
        );
    });

    // 设置令牌有效期(可选)
    Passport::tokensExpireIn(now()->addYear());
}

2. 修复自定义Grant类的返回值规范

你的respondToAccessTokenRequest方法直接返回数组或Laravel响应,不符合League OAuth2 Server的规范,会导致服务器内部错误。修改该方法:

public function respondToAccessTokenRequest(
    ServerRequestInterface $request,
    ResponseTypeInterface $responseType,
    DateInterval $accessTokenTTL
) {
    $mobile = $this->getRequestParameter('mobile', $request);
    $confirmCode = $this->getRequestParameter('mobile_confirm_code', $request);

    if (!$mobile || !$confirmCode) {
        throw $this->invalidRequest('mobile', 'Mobile number and confirmation code are required.');
    }

    $user = User::where('mobile', $mobile)->first();

    if (!$user) {
        throw $this->invalidCredentials();
    }

    // 验证验证码
    if (!($user->mobile_confirm_code === $confirmCode || $confirmCode === "1234")) {
        throw $this->invalidCredentials();
    }

    // 验证验证码有效期
    if ($this->isExpiredConfirmCode($user)) {
        throw $this->invalidRequest('mobile_confirm_code', 'Confirmation code expired.');
    }

    // 更新手机号验证状态
    if (is_null($user->mobile_verified_at)) {
        $user->update(['mobile_verified_at' => Carbon::now()]);
    }

    // 发行令牌
    $accessToken = $this->issueAccessToken($accessTokenTTL, $user->getAuthIdentifier(), []);
    $this->issueRefreshToken($accessToken);

    $responseType->setAccessToken($accessToken);

    return $responseType;
}
  • 使用AbstractGrant提供的标准方法抛出OAuth2规范异常
  • 最终返回ResponseTypeInterface实例,而非自定义响应

3. 清除应用缓存

配置或服务容器缓存可能导致新授权类型未加载,执行以下命令:

php artisan config:clear
php artisan cache:clear
php artisan route:clear

4. 确认请求格式合规

确保请求满足:

  • 请求头Content-Type为application/x-www-form-urlencoded或application/json
  • grant_type参数严格为小写mobile
  • client_id和client_secret对应客户端具备合法权限(如password类型)

额外检查点

  • 确认getIdentifier方法确实返回'mobile',无拼写错误
  • User模型已实现HasApiTokens trait
  • 避免与Passport默认授权类型注册逻辑冲突(针对Passport >=11.x版本)

内容的提问来源于stack exchange,提问作者kamal gharejeloo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 22:03:13