Google OAuth2 returns “unsupported_grant_type” via cURL (PHP)

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

I want to get data about google account. I use next code:

$curl = curl_init();  curl_setopt_array($curl, array(     CURLOPT_URL => 'https://www.googleapis.com/oauth2/v4/token',     CURLOPT_CUSTOMREQUEST => "POST",     CURLOPT_RETURNTRANSFER => true,     CURLOPT_TIMEOUT => 30,     CURLOPT_HTTPHEADER => [         'Cache-Control: no-cache',         'Content-Type: application/x-www-form-urlencoded',     ],     CURLOPT_POSTFIELDS => [         'code' => $code,         'client_id' => '{MY_CLIENT_ID}',         'client_secret' => '{MY_CLIENT_SECRET}',         'redirect_uri' => '{SOME_URL}'         'grant_type' => 'authorization_code',     ] ));  $result = curl_exec($curl); $err = curl_error($curl);  curl_close($curl); 

In result I get next error:

{     "error": "unsupported_grant_type",     "error_description": "Invalid grant_type: " } 

I use instructions from this:

https://developers.google.com/identity/protocols/OpenIDConnect

Variable $code and another data are valid! Because I try to send request via "PostMan" and there I get correct result.

Tell me please, where I have mistake?

回答1:

Try to do that in this way:

$curl = curl_init();  curl_setopt_array($curl, array(     CURLOPT_URL => 'https://www.googleapis.com/oauth2/v4/token',     CURLOPT_POST => true,     CURLOPT_RETURNTRANSFER => true,     CURLOPT_TIMEOUT => 30,     CURLOPT_POSTFIELDS => http_build_query([         'code' => $code,         'client_id' => '{MY_CLIENT_ID}',         'client_secret' => '{MY_CLIENT_SECRET}',         'redirect_uri' => '{SOME_URL}'         'grant_type' => 'authorization_code',     ]), )); 

BTW, you can debug curl requests using

CURLOPT_VERBOSE => true, 


回答2:

I was doing this in c# and think my issue could be related. When specifying the redirect_url or any other string, make sure you escape the URI otherwise it will mess up the post request. This is because the request is sent using application/x-www-form-urlencoded type.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!