dqhnp44220 2014-06-05 11:04
浏览 81
已采纳

PHP - 将OAuth 2.0用于服务器到服务器应用程序 - 授权无效

I'm trying to use the Google Api Calendar, but I'm not able to pass the auth step.

Following this tutorial, I've written some php code (yes, I know, I should use the API) that gives me "invalid grant" as response.

I'm very diehard and I really would know where my error is. I suppose is the sign step, but the private_key is a valid struct. I obtained the .pem by converting the p12 using this command:

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

Could you please help me?

Thanks.

<?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)
?>
  • 写回答

1条回答 默认 最新

  • duanmuyao0463 2014-06-06 07:28
    关注

    When computing the signature, you need to concatenate the header and claim set with a dot '.', i.e., $header . '.' . $jwt_cs. When building the JWT, you also need to concatenate the header, claim set and signature with a dot '.', i.e., $header . '.' . $jwt_cs . '.' . $sign.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog