问题
I'm trying to sign a request for Google 0Auth2 (in PHP) Here's my code:
$jwtHeader = $this->base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));
$now = time();
$jwtClaim = $this->base64url_encode(json_encode(array(
"iss" => "xxxxxxxxxxxxxxx.xxx.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/prediction",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"iat" => $now,
"exp" => $now + 3600,
)));
$sign = hash_hmac('SHA256', $jwtHeader.".".$jwtClaim, $secret);
$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$sign;
$client = new \GuzzleHttp\Client();
$res = $client->post('https://www.googleapis.com/oauth2/v4/token', ['headers' => ['Content-Type: application/x-www-form-urlencoded'], 'form_params' => ['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwtAssertion]]);
if ($res->getStatusCode() == 200) {
return $res->getBody()->getContents();
}
//BASE64 METHOD
public function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
The response I get is
{
"error": "invalid_grant",
"error_description": "Invalid JWT Signature."
}
Been on this for some hours now, still getting same error. Anyone come across this? I would appreciate any suggestion.
回答1:
Okay for the sake of those that might encounter the same issue. This how I solved it:
$jwtHeader = $this->base64url_encode(json_encode(array(
"alg" => "RS256",
"typ" => "JWT"
)));
$now = time();
$jwtClaim = $this->base64url_encode(json_encode(array(
"iss" => "xxxxxxxxxxxxxxxxxx.xxx.gserviceaccount.com",
"scope" => "https://www.googleapis.com/auth/prediction",
"aud" => "https://www.googleapis.com/oauth2/v4/token",
"iat" => $now,
"exp" => $now + 3600,
)));
$secret = "-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n";
$binary_signature = "";
$algo = "SHA256";
openssl_sign($jwtHeader.".".$jwtClaim, $binary_signature, $secret, $algo);
$jwtSign = $this->base64url_encode($binary_signature);
$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$jwtSign;
$client = new \GuzzleHttp\Client();
$res = $client->post('https://www.googleapis.com/oauth2/v4/token', ['headers' => ['Content-Type: application/x-www-form-urlencoded; charset=utf-8'], 'form_params' => ['grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => $jwtAssertion]]);
if ($res->getStatusCode() == 200) {
return $res->getBody()->getContents();
}
public function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
This works as expected.
来源:https://stackoverflow.com/questions/48106432/invalid-signature-google-jwt-api