dqhnp44220
dqhnp44220
2014-06-05 11:04

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 duanmuyao0463 7年前

    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.

    点赞 评论 复制链接分享