我正试图为我的CloudFi还原API生成一个访问令牌,我一直收到以下错误:-
{"error":"invalid_grant","error_description":"Invalid JWT Signature."}
编辑:从我的代码中删除urldecode将导致显示无效签名。
我想要生成一个Oauth令牌,而不让用户使用任何形式的Firebase身份验证,因为这不是我的web应用的用例。
我跟踪了https://developers.google.com/identity/protocols/oauth2/service-account的文档,我只使用了文档中提到的端点。
<?php
$config = json_decode('service_account_key',true);
$jwt_header = '{"alg":"RS256","typ":"JWT"}';
$jwt_header_cryph = urlencode(base64_encode($jwt_header));
$jwt_claim = '{
"iss": "service_account_id",
"scope":"https://www.googleapis.com/auth/datastore",
"aud":"https://oauth2.googleapis.com/token",
"exp":'.(time()+3600).',
"sub": "user_email"
"iat":'.time().'
}';
$jwt_claim_cryph = urlencode(base64_encode($jwt_claim));
$data = $jwt_header_cryph.".".$jwt_claim_cryph;
$binary_signature = "";
$algo = "SHA256";
openssl_sign($data, $binary_signature, $config['private_key'], $algo);
$jws_signature_cryph = urlencode(base64_encode($binary_signature));
$complete_request = $jwt_header_cryph.".".$jwt_claim_cryph.".".$jws_signature_cryph;
$curl_url = 'https://oauth2.googleapis.com/token';
$fields = array(
'grant_type' => urlencode('urn:ietf:params:oauth:grant-type:jwt-bearer'),
'assertion' => $complete_request
);
$fields_string = "";
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $curl_url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
$token = json_decode($result, true);
echo($token);
发布于 2022-04-03 19:14:28
不要使用urlencode。该步骤不会在headers上执行,并且会破坏base64编码。签名验证是对您传递的数据执行的,而不是在URL解码之后执行的。
链接到我编写的一个Python示例,这样您就可以比较代码了。使用Python代码查看每个步骤生成的内容。
您可以通过调用以下端点来验证访问令牌:
curl -H "Authorization: Bearer $ACCESS_TOKEN" https://www.googleapis.com/oauth2/v3/tokeninfo
curl -H "Authorization: Bearer $ACCESS_TOKEN" https://www.googleapis.com/oauth2/v3/userinfo
第一个端点返回有关访问令牌的信息。
第二个端点请求OIDC标识令牌。当您使用其他需要基于身份的授权的Google服务时,这将是非常有用的。
https://stackoverflow.com/questions/71723641
复制相似问题