Invalid JWT when trying to connect to Google Oauth for Google APIs

I tried to connect to the Google API through OAuth via JWT, but I keep getting this error:

{"error": "invalid_grant", "error_description": "Invalid JWT: the token must be a short-term token and within a reasonable time"}

In my JWT calim, I installed iat at the current time minus 1970-01-01 in seconds and exp to iat + 3600, so I don’t know why I am still getting this error. If anyone knows the answer, please let me know.

+4
source share
4 answers

, - , PHP openssl_sign():

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

//Google 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;
+1

, . :

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

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

I had the same problem, I solved it by synchronizing the time of my virtual machine to have the correct version with open ntpserver:

ntpdate ntp.ubuntu.com
0
source

All Articles