Unsupported content with type: multipart/form-data in google plus api oauth2

心不动则不痛 提交于 2019-12-05 15:41:08

You request is correct but missing something the content type is not multipart/form-data should be application/x-www-form-urlencoded instead

gheni4

I had very similar problem using OAuth2.0 to access Gmail from iOS app. Indeed Ahmad's suggestion is correct I'll expand it:

When you POST using HTTP there is a header field 'Content-Type:'. Looks like in your case it had default value of 'multipart/form-data' which is for binary data. For Google API OAuth2.0 make sure you set it to 'application/x-www-form-urlencoded'.

You can see this value in the example given here: https://developers.google.com/identity/protocols/OAuth2InstalledApp#handlingtheresponse

You can read more about those two values for 'Content-Type' here: application/x-www-form-urlencoded or multipart/form-data?

In my iOS framework I had to make a call to customize this HTTP header. Unfortunately I'm not familiar with PHP so hope that helps.

I had a very similar problem. I was finally able to resolve it by adding some elements to the HTTP header ("Content-Type" and "Content-Length") and manually constructing the url (so I can use 0 for "Content-Length").

$id_token = $_POST['id_token'];
$url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token='.$id_token;
$options = [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_POST => 1,
    CURLOPT_HTTPHEADER => array( "Content-Length: 0", "Content-Type: application/x-www-form-urlencoded"),
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_SSL_VERIFYPEER => false,
];

$curlObj = curl_init();
curl_setopt_array($curlObj, $options);
$returnData = curl_exec($curlObj);
if (curl_errno($curlObj)) {
    //error message
    $returnData = curl_error($curlObj);
}

echo $returnData;
      if(isset($_REQUEST['code'])){
$ch =curl_init();
$auth_url = "https://www.googleapis.com/oauth2/v4/token";
$post = array(
        'code' =>$_REQUEST['code'],
        'client_id' => '**************',
        'client_secret' => '************',
        'redirect_uri' => 'http://localhost/prakash/redirect.php',
        'grant_type' => 'authorization_code'
        );
$postText = http_build_query($post);
$options = array(
    CURLOPT_URL =>$auth_url,
    CURLOPT_POST => true,
     CURLOPT_SSL_VERIFYPEER =>false,
    CURLOPT_RETURNTRANSFER =>true,
    CURLOPT_POSTFIELDS => $postText
);
//print_r($ch);
curl_setopt_array($ch, $options);
$returnData = curl_exec($ch);
print_r($returnData);
curl_close($ch);
    exit;
}else{
    print_r($_REQUEST);
    exit;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!