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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动