我正在尝试签署Google 0Auth2的请求(在PHP中) 这是我的代码:
$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), '+/', '-_'), '=');
}
我得到的回应是
{
"error": "invalid_grant",
"error_description": "Invalid JWT Signature."
}
现在已经持续了几个小时,仍然得到同样的错误。有人碰到过这个吗? 我很感激任何建议。
答案 0 :(得分:0)
好的,为了那些可能遇到同样问题的人。这就是我解决它的方法:
$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), '+/', '-_'), '=');
}
这可以按预期工作。