【问题标题】:PHP - Using OAuth 2.0 for Server to Server Applications - Invalid grantPHP - 将 OAuth 2.0 用于服务器到服务器应用程序 - 授权无效
【发布时间】:2014-07-26 08:22:01
【问题描述】:

我正在尝试使用 Google Api 日历,但我无法通过身份验证步骤。

tutorial 之后,我编写了一些 php 代码(是的,我知道,我应该使用 API)给我“无效授权”作为响应。

我非常顽固,我真的会知道我的错误在哪里。我想是符号步骤,但 private_key 是一个有效的结构。我通过使用以下命令转换 p12 获得了 .pem:

openssl pkcs12 -in key.p12 -out key.pem -nodes

你能帮帮我吗?

谢谢。

<?php
$private_key = openssl_pkey_get_private('file://key.pem', 'notasecret');

$header = array("alg" => "RS256", "typ" => "JWT");
$header = base64_encode(utf8_encode(json_encode($header)));
$exp = time() + (60 * 60); 

$jwt_cs = array(
   "iss" => "************************@developer.gserviceaccount.com",
   "scope" => "https://www.googleapis.com/auth/calendar.readonly",
   "aud" => "https://accounts.google.com/o/oauth2/token",
   "exp" => $exp,
   "iat" => time(),
   "access_type" => "offline"
);
$jwt_cs = base64_encode(utf8_encode(json_encode($jwt_cs)));
openssl_sign($header.$jwt_cs, $sign, $private_key, 'sha256WithRSAEncryption');

$sign = base64_encode($sign);

$jwt = $header.$jwt_cs.$sign;

$login_data = array(
    'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion' => $jwt
);
$url='https://accounts.google.com/o/oauth2/token';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($login_data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = json_decode(curl_exec($ch));
curl_close($ch);
var_dump($res)
?>

【问题讨论】:

  • 我不确定 jwt 数组中的 access_type。我试图在没有它的情况下启动这个脚本,但错误是一样的。

标签: php oauth-2.0 google-calendar-api


【解决方案1】:

计算签名时,需要用点“.”连接头部和声明集,即$header . '.' . $jwt_cs。 在构建 JWT 时,您还需要将标头、声明集和签名用点“.”连接起来,即$header . '.' . $jwt_cs . '.' . $sign

【讨论】:

  • 哎哟!我将点字符与 concat 运算符混淆了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 1970-01-01
  • 2016-08-12
  • 1970-01-01
  • 2012-11-18
相关资源
最近更新 更多