从访问令牌护照获取密码客户端 laravel

get password client from access token passport laravel

我在 laravel 中使用护照,在用户验证后我想为他们生成一个带有刷新令牌的令牌。为了获取刷新令牌,我必须使用 password grant_type 发送 curl 请求。生成访问令牌后,我想从数据库中获取 Password Grant Client 并将其传递给我的 curl 主体。我找到了这个代码片段:

 $tokenId = (new Parser(new JoseEncoder()))->parse($token)->claims()->get('jti');
 $client = \Laravel\Passport\Token::find($tokenId)->client;

并且客户端变量的问题结果是 Personal Access Client 而不是 Password Grant Client 并且因为它的 personal type:

而得到这个错误
{
    "error": "invalid_client",
    "error_description": "Client authentication failed",
    "message": "Client authentication failed"
}
    

这是我的代码:

$token = $user->createToken(Config::get('auth.guards.api.token_name'))->accessToken;
        $tokenId = (new Parser(new JoseEncoder()))->parse($token)->claims()->get('jti');
        $client = \Laravel\Passport\Token::find($tokenId)->client;

        $http = new \GuzzleHttp\Client();
        try {
            $response = $http->request('POST', url("/oauth/token"), [
                'form_params' => [
                    'grant_type' => 'password',
                    'client_id' => $oClient->id,
                    'client_secret' => $oClient->secret,
                    'username' => $username,
                    'password' => $password,
                    'scope' => '*',
                ],
            ]);
        } catch (\Exception $exception) {
        }

我该如何处理?

要为 Password Grant Client 获取 client_idclient_secret,您需要 运行 在您的授权服务器(OAuth 服务器)上执行以下命令,如此处所述 https://laravel.com/docs/9.x/passport#creating-a-password-grant-client

php artisan passport:client --password

如果您已经 运行 passport:install,则 运行 不需要上述命令。最简单的方法是检查 oauth_clients table 列的 password_client 应该有一行将此值设置为 1(启用)。

从您的问题看来,您正试图以编程方式从您的客户端获取 client_idclient_secret。这不是正确的做法。 基本上在你 运行 上面的命令生成你的 client_idclient_secret 你需要在你的 .env 中硬编码它们并在你的 CURL 中使用它们,例如:


$response = Http::asForm()->post('http://passport-app.test/oauth/token', [
    'grant_type' => 'password',
    'client_id' => env('OAUTH_CLIENT_ID'),
    'client_secret' => env('OAUTH_CLIENT_SECRET'),
    'username' => $username,
    'password' => $password,
    'scope' => '*',
]);
 
return $response->json();

您可以从 oauth_clients table 中获得您的 client_idclient_secret。只需确保复制 password_client 列设置为 1 的值。

如果您的客户端将这些凭据存储在后端并从后端执行 CURL,则不应有任何安全问题。

如果您尝试通过移动应用执行此操作,并且您可能无法安全地存储 client_idclient_secret。在这种情况下,您不应使用 Password Grant Client 流程,而应使用 Authorization Code Grant with PKCEhttps://laravel.com/docs/9.x/passport#code-grant-pkce