PHP获取令牌Oauth PKCE

x8diyxa7  于 2023-02-28  发布在  PHP
关注(0)|答案(1)|浏览(115)

我想从Oauth服务器获取令牌。我使用用户名和密码登录浏览器,Oauth服务器返回此URL:
http:/example.com/callback?code=D3F7A9B42EA49F92EACC21ECC60AA7187A71DAD85E4478FB8724BB0444054D39&scope=tts_api&iss=https://oauthserver.com
用于处理此方法中使用的回调

public function handleAauth(Request $request)
    {
        $http = new Client;
        $code_verifier = bin2hex(random_bytes(32));
        $code_challenge = hash('sha256', $code_verifier, true);

        $response = $http->post('https://outh-server.com/connect/token', [
          'form_params' => [
            'grant_type' => 'authorization_code',
            'client_id' => 'my-client-id',
            'code_verifier' => $code_verifier,
            'code' => $request->code,
            'code_challenge' => $code_challenge,
            'redirect_uri' => 'http://example.com/callback',
          ],
          'headers' => ['Accept' => 'application/json']
        ]);

        return $response->getBody()->getContents();
    }

当使用此代码进行回调时,返回此错误:

Client error: `POST https://outh-server.com/connect/token` resulted in a `400 Bad Request` response: {"error":"invalid_request"}

请帮帮我。

rks48beu

rks48beu1#

另一种解决方案是使用json键而不是form_params来将请求有效负载作为JSON对象发送。

public function handleAauth(Request $request)
{
    $http = new Client;
    $code_verifier = bin2hex(random_bytes(32));
    $code_challenge = hash('sha256', $code_verifier, true);

    $response = $http->post('https://outh-server.com/connect/token', [
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
        ],
        'json' => [
            'grant_type' => 'authorization_code',
            'client_id' => 'my-client-id',
            'code_verifier' => $code_verifier,
            'code' => $request->code,
            'code_challenge' => $code_challenge,
            'redirect_uri' => 'http://example.com/callback',
        ]
    ]);

    return $response->getBody()->getContents();
}

尝试向代码中添加更具体的错误处理,以获取有关错误响应的更多信息。例如,可以捕获GuzzleHttp\Exception\ClientException异常并检查响应正文和标头:

try {
    // Make API request
} catch (GuzzleHttp\Exception\ClientException $e) {
    // Get response details
    $response = $e->getResponse();
    $statusCode = $response->getStatusCode();
    $reasonPhrase = $response->getReasonPhrase();
    $body = $response->getBody()->getContents();

    // Log error details or handle the error in some other way
}

相关问题