错误“invalid_grant/无效的 JWT 签名。”使用 Oauth 获取访问令牌

问题描述 投票:0回答:2

长期以来我一直在尝试解决这个问题。 我需要使用服务帐户生成令牌访问权限才能使用 Google 日历应用程序。 首先,我使用基于 pem 证书的 firebase / php-jwt 库执行 JWT,其中存储了 Google 服务帐户提供的私钥 在 Google 中执行curl 操作以获取上述令牌后,它会抛出以下错误““ invalid_grant / Invalid JWT Signature”

$time = time();

$key = file_get_contents("./certs/certificado.pem");
$token = array(
    "iss" => "*****@*******.iam.gserviceaccount.com",
    "aud" => "https://www.googleapis.com/oauth2/v3/token",
    "iat" => $time,
    "exp" => $time+60,
    "scope" => "https://www.googleapis.com/auth/calendar.readonly"
);

$jwt = JWT::encode($token, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));
echo $jwt;
print_r($decoded);

$decoded_array = (array) $decoded;
$grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer";

JWT::$leeway = 600; 
$decoded = JWT::decode($jwt, $key, array('HS256'));

我向 Google 进行卷曲以获取访问令牌的示例

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://www.googleapis.com/oauth2/v3/token");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"grant_type=".urlencode($grant_type)."&assertion=".urlencode($jwt));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close ($ch);
echo($result);

Google 给出以下错误

{
  "error": "invalid_grant",
  "error_description": "Invalid JWT Signature."
}
php google-oauth access-token jwt
2个回答
0
投票

您对 Google OAuth 使用了错误的签名算法。使用RS256。

接下来,一旦您拥有签名的 JWT,就可以将其交换为访问令牌。

本文向您展示了使用 Python 的详细信息:链接

本文向您展示了使用 CURL 的详细信息:链接


0
投票

就我而言,我用错了

service account ID

您可以在以下位置找到正确的内容: Google 控制台 -> 服务帐户 -> 详细信息 -> 唯一 ID

我必须是一个很长的数字,例如:223334445551115551234

© www.soinside.com 2019 - 2024. All rights reserved.