尝试连接到 Google Oauth for google API 时 JWT 无效 [英] Invalid JWT when trying to connect to Google Oauth for google API

查看:20
本文介绍了尝试连接到 Google Oauth for google API 时 JWT 无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 JWT 通过 OAuth 连接到 Google API,但我不断收到此错误:

I was trying to connect to Google API through OAuth through JWT, but I keep getting this error:

{ "error": "invalid_grant", "error_description": "Invalid JWT: Token 必须是短命的 token 并且在合理的时间范围内" }

{ "error": "invalid_grant", "error_description": "Invalid JWT: Token must be a short-lived token and in a reasonable timeframe" }

在我的 JWT calim 中,我将 iat 设置为当前时间减去 1970-01-01 以秒为单位,并将 exp 设置为 iat + 3600,所以我不知道为什么我仍然收到此错误.如果有人知道答案,请告诉 meeeeee!

In my JWT calim I set the iat to be current time minus 1970-01-01 in seconds and exp to iat + 3600, so I do not know why I am still getting this error. If anyone knows the answer please tell meeeeee!

推荐答案

不确定你是否曾经让它工作,但使用 PHP 函数 openssl_sign():

Not sure if you ever got it to work, but the following simple steps worked for me using the PHP function openssl_sign():

//helper function
function base64url_encode($data) { 
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

//Google's Documentation of Creating a JWT: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
    "alg" => "RS256",
    "typ" => "JWT"
)));
//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
    "iss" => "761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
    "scope" => "https://www.googleapis.com/auth/prediction",
    "aud" => "https://www.googleapis.com/oauth2/v4/token",
    "exp" => $now + 3600,
    "iat" => $now
)));
//The base string for the signature: {Base64url encoded JSON header}.{Base64url encoded JSON claim set}
openssl_sign(
    $jwtHeader.".".$jwtClaim,
    $jwtSig,
    $your_private_key_from_google_api_console,
    "sha256WithRSAEncryption"
);
$jwtSign = base64url_encode($jwtSig);

//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.{Base64url encoded signature}
$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$jwtSig;

这篇关于尝试连接到 Google Oauth for google API 时 JWT 无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆