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

如何在Laravel Passport的PKCE模式下自动生成授权码(无需Laravel UI)

Laravel Passport PKCE模式下生成授权码的无路由方案

核心思路

直接调用Laravel Passport内置的AuthorizationCodeGrant类及配套服务,复用官方已经实现的授权码生成、存储逻辑,完全不用手动写存库代码,也不依赖默认的oauth/authorize路由。

具体实现步骤

1. 注入Passport核心依赖

在你自定义的API控制器顶部引入以下类:

use Laravel\Passport\Bridge\AuthorizationCodeGrant;
use Laravel\Passport\Bridge\ClientRepository;
use Laravel\Passport\Bridge\UserRepository;
use League\OAuth2\Server\Exception\OAuthServerException;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Illuminate\Http\Request;

2. 校验客户端合法性

先通过ClientRepository校验传入的客户端ID是否有效,同时确认客户端配置符合要求:

public function getAuthorizationCode(Request $request)
{
    $clientId = $request->input('client_id');
    $clientRepository = app(ClientRepository::class);
    $client = $clientRepository->getClientEntity($clientId);

    // 客户端不存在时抛出OAuth标准异常
    if (!$client) {
        throw OAuthServerException::invalidClient();
    }

    // 校验客户端是否配置了回调地址(PKCE模式必需)
    if (!$client->getRedirectUri()) {
        throw OAuthServerException::invalidRequest('redirect_uri', '客户端未配置回调地址');
    }

3. 校验用户凭证并生成授权码

先验证客户端传入的用户名密码,再调用Passport的授权码生成逻辑:

// 校验用户账号密码
    $user = User::where('email', $request->input('email'))->first();
    if (!$user || !Hash::check($request->input('password'), $user->password)) {
        throw OAuthServerException::invalidCredentials();
    }

    // 处理PKCE参数:按你的流程用code_verifier生成challenge(标准PKCE建议客户端传challenge)
    $codeVerifier = $request->input('code_verifier');
    $codeChallenge = hash('sha256', $codeVerifier);
    $codeChallengeMethod = 'S256';

    // 获取Passport的授权码生成实例
    $grant = app(AuthorizationCodeGrant::class);
    $userRepository = app(UserRepository::class);

    // 生成授权码(Passport会自动处理存储到oauth_authorization_codes表)
    $authorizationCode = $grant->issueAuthorizationCode(
        $client,
        $userRepository->getUserEntityByUserCredentials(
            $request->input('email'),
            $request->input('password'),
            'password',
            $client
        ),
        $client->getRedirectUri()
    );

    // 返回授权码及相关信息
    return response()->json([
        'authorization_code' => $authorizationCode->getIdentifier(),
        'expires_in' => $grant->getAuthorizationCodeTTL()->getTimestamp() - time(),
        'code_challenge_method' => $codeChallengeMethod
    ]);
}

4. 关键注意事项

  • 确保已完成Laravel Passport的基础安装和数据库迁移,oauth_authorization_codes表必须存在
  • 标准PKCE流程中,客户端应传递code_challenge而非code_verifier,建议调整流程符合规范,降低安全风险
  • 授权码过期时间可在config/passport.php中修改authorization_code_ttl参数,默认5分钟
  • 所有异常需返回符合OAuth2规范的错误响应,方便前端识别处理

内容的提问来源于stack exchange,提问作者noa-developer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 04:37:19