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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测