0

I am testing the Google Speech API. I want to use JWT to get access token.

However, when I get the access token. It return:

"error": "invalid_grant", "error_description": "Invalid JWT Signature."

Here is my code:

$expire_time=strtotime("+30 min");

$current_time=strtotime("now");

$h='{"alg":"RS256","typ":"JWT"}';

$h=str_replace("\r\n", "", $h);

$base64_h=base64_encode($h);

$base64_h=str_replace("=", "", $base64_h);

$base64_h=str_replace("+", "-", $base64_h);

$base64_h=str_replace("/", "_", $base64_h);


$c='
{"iss":"My ISS",
"scope":"https://www.googleapis.com/auth/prediction","aud":"https://www.googleapis.com/oauth2/v4/token","exp":'.$expire_time.',"iat":'.$current_time.'}';


$c=str_replace("\r\n", "", $c);

$base64_c=base64_encode($c);

$base64_c=str_replace("=", "", $base64_c);

$base64_c=str_replace("+", "-", $base64_c);

$base64_c=str_replace("/", "_", $base64_c);


$secret="My Secret";

$sig_input=$base64_h.".".$base64_c;

$sig = hash_hmac('sha256', $sig_input,$secret);

$base64_sig=base64_encode($sig);

$base64_sig=str_replace("=", "", $base64_sig);

$base64_sig=str_replace("+", "-", $base64_sig);

$base64_sig=str_replace("/", "_", $base64_sig);

$JWT=$base64_h.".".$base64_c.".".$base64_sig;
aljo f
  • 2,430
  • 20
  • 22

1 Answers1

0

I got the answer The code should be:

    $private_key = your private_key
    $sig_input=$base64_h.".".$base64_c;
    //input for sign:
        //{Base64url encoded header}.{Base64url encoded claim set}

        $sig_input=$base64_h.".".$base64_c;

        //create signature      
        openssl_sign(
                $sig_input,
                $sig,
                $private_key,
                "sha256WithRSAEncryption"
        );

        $base64_sig=base64json_encode($sig);

        //JWT = {Base64url encoded header}.{Base64url encoded claim set}.{Base64url encoded signature}
        $JWT=$base64_h.".".$base64_c.".".$base64_sig;
John
  • 1