Invalid JWT when trying to connect to Google Oauth for google API

寵の児 提交于 2019-12-22 08:26:44

问题


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 must be a short-lived token and in a reasonable timeframe" }

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!


回答1:


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;



回答2:


You have to set a correct expiration time for the token if you see this error. Example:

var currentTime = new Date().getTime() / 1000; //must be in seconds
var exp = currentTime + 60;

var auth_claimset = {
      iss       :   "...",
      scope     :   "...",
      aud       :   "...",
      exp       :   exp,
      iat       :   currentTime 
};



回答3:


I had the same issue, I solved it by syncing my VMs time to have the correct one with a public ntpserver:

ntpdate ntp.ubuntu.com



回答4:


If you are following the steps under HTTP/Rest here: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#formingheader, you'll see that your service accounts support RSA SHA-256, and you appear to use HMAC.



来源:https://stackoverflow.com/questions/36909121/invalid-jwt-when-trying-to-connect-to-google-oauth-for-google-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!