Google API OAuth2.0身份验证问题:无法获得正确的响应

时间:2019-05-26 07:41:28

标签: php google-api jwt google-oauth2

我正在尝试遵循本指南https://developers.google.com/identity/protocols/OAuth2ServiceAccount#callinganapi来生成Json网络令牌(JWT)。

我已经看到诸如Google API OAuth 2.0 authentication returning "invalid_grant" - possible private key signature format issue?之类的问题,并且正在遵循解决方案和建议来构建自己的请求。我正在使用的代码如下:

$JWT_Header = array("alg" => "RS256","typ" => "JWT");
$now = time();
$JWT_Body = array(
  "iss" => "client_email_in_json_file",
  "scope" => "https://www.googleapis.com/auth/cloud-translation",
  "aud" => "https://www.googleapis.com/oauth2/v4/token",
  "exp" => $now+3600,
  "iat" => $now
];
$jwtHeader = rtrim(strtr(base64_encode(json_encode($JWT_Header)), '+/', '-_'), '=');
$jwtClaim rtrim(strtr(base64_encode(json_encode($JWT_Body)), '+/', '-_'),'=');
$private_key =
  "-----BEGIN PRIVATE KEY-----This_is_a_private_key-----END PRIVATE KEY-----\n";
$jwtSig = null;
openssl_sign(
  $jwtHeader.".".$jwtClaim,
  $jwtSig,
  $private_key,
  "sha256WithRSAEncryption"
);
$jwtSig =rtrim(strtr(base64_encode($jwtSig), '+/', '-_'), '=');

$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$jwtSig;
$headers = array(
  'Host: accounts.google.com',
  'Content-Type: application/x-www-form-urlencoded'
);
$fields = array(
 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
 'assertion'  => PHP\urlencode($jwtAssertion)
);
$fields_string = '';
foreach($fields as $key => $value) $fields_string .= '&'.$key.'='.$value;
$fields_string = substr($fields_string, 1);
$ch = PHP\curl_init();
$url = 'https://accounts.google.com/o/oauth2/token';
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_HEADER, TRUE );
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, PHP\count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1 );
$result = curl_exec($ch);
curl_close($ch);

我希望获得一个正确的访问令牌作为$ response,但是运行这段代码后,我只能得到$ result = false。可能有任何理由获得此回复吗?感谢任何帮助!

0 个答案:

没有答案