在PHP中卷曲以获取access_token OAuth2返回错误:" invalid_client"

时间:2017-10-15 18:39:45

标签: php laravel curl oauth-2.0 laravel-5.2

从OAuth2 Server获取access_token时遇到问题。我在PHP中使用curl来获取access_token,但它失败并返回:

error: "invalid_client",
error_description: "Client authentication failed."

奇怪的是,如果我在命令提示符下使用curl:

curl -d "client_id=f3d259ddd3ed8ff3843839b&client_secret=4c7f6f8fa93d59c45502c0ae8c4a95b&redirect_uri=http://application.dev/oauth/handle&grant_type=authorization_code&code=rZCQQBXVSQqKi2IRro1gYkSsRhyUcLsNODACjwPw" http://oauth-server.dev/oauth/access_token

成功并返回access_token:

"access_token":"fI7APDRZygrsF1BiegAQCS1yUT8vnm1LgD5bIu2U",
"token_type":"Bearer",
"expires_in":3600

我使用的是Laravel 5.2,我的代码是从OAuth Server处理来获取access_token:

public function getOAuthHandle(Request $request){
    $url = 'http://oauth-server.dev/oauth/access_token';
    $code = $request->code;
    $client_id = 'f3d259ddd3ed8ff3843839b';
    $client_secret = '4c7f6f8fa93d59c45502c0ae8c4a95b';
    $redirect_uri = 'http://application.dev/oauth/handle';

    $clienttoken_post = array(
                "code" => $code,
                "client_id" => $client_id,
                "client_secret" => $client_secret,
                "redirect_uri" => $redirect_uri,
                "grant_type" => "authorization_code"
            );

            $curl = curl_init($url);

            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
            curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

            $json_response = curl_exec($curl);
            curl_close($curl);

            return $json_response;
}

我尝试过来自互联网和stackoverflow的另一个脚本并重启Apache和PHP,但它仍然无法正常工作。

有什么方法可以解决这个问题吗?我该怎么检查?

感谢您的帮助和回答。

1 个答案:

答案 0 :(得分:0)

尝试在curl标头上发送请求。

    $curl = \curl_init();

    \curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 600,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_HTTPHEADER => $clienttoken_post,
        CURLINFO_HEADER_OUT => true,
    ));

    $response = \curl_exec($curl);

在标题上发送了grant_type,然后在client_secretclient_id发送了帖子,或者在标题上发送它们。顺便说一下。在传递给curl请求之前应该检查$request->code。所有url, client_secret, client_id必须在.env中,并通过config/services