Google API OAuth2:使用 Perl 请求服务帐户令牌时出现“invalid_grant"错误 [英] Google API OAuth2 : “invalid_grant” error when requesting token for Service Account with Perl

查看:44
本文介绍了Google API OAuth2:使用 Perl 请求服务帐户令牌时出现“invalid_grant"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从开发者控制台获得了服务帐户的凭据

Got the credentials for Service Account from Developer Console

首先,我将 p12 私钥转换为 PEM:

First, I converted p12 private key to PEM:

openssl pkcs12 -in <private key for Service Account>.p12 -out calendar.key -nocerts -nodes

然后我跑:

use MIME::Base64;
use Crypt::OpenSSL::RSA;
use File::Slurp;

my $header = encode_base64('{"alg":"RS256","typ":"JWT"}','');
my $claim = encode_base64('{
"iss":"<mail for the Service Account>",
"scope":"https://www.googleapis.com/auth/calendar",
"aud":"https://accounts.google.com/o/oauth2/token",
"exp":'.(time()+3600).',
"iat":'.time().'
}','');

my $key = read_file('calendar.key');
my $rsa = Crypt::OpenSSL::RSA->new_private_key($key);
$rsa->use_sha256_hash;
$rsa->use_pkcs1_padding;
my $signature = encode_base64($rsa->sign($header . '.' . $claim), '');

my $token_request = $header . '.' . $claim . '.' . $signature;

print `curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$token_request' https://accounts.google.com/o/oauth2/token`;

我明白了

{
  "error" : "invalid_grant"
}

我用 NTP 同步了系统时间,没有帮助.

I synchronized the system time with NTP, didn't help.

推荐答案

我不知道为什么,但问题出在 curl.

I don't know why, but the problem was with curl.

我将其替换为 WWW::Mechanize:

I replaced it by WWW::Mechanize:

my $mech = WWW::Mechanize->new( autocheck => 1 );
$mech->post('https://accounts.google.com/o/oauth2/token',
    'Content-Type' => 'application/x-www-form-urlencoded',
    'Content' => [
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $token_request,
    ],
);

它有效.

这篇关于Google API OAuth2:使用 Perl 请求服务帐户令牌时出现“invalid_grant"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆