如何使用 Mojo::UserAgent 向 Oauth 授权请求?
How can I make a request authorized with Oauth with Mojo::UserAgent?
我目前正在尝试完成这项工作:
my $ua = Mojo::UserAgent->new;
my $req = Mojo::Message::Request->new;
my $tx = $ua->build_tx(GET => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full');
app->log->info($c->session('token'));
$tx->req->headers->authorization('Bearer ' . $c->session('token'));
其中 $c->session('token')
是我通过 Mojolicious::Plugin::OAuth2 获得的令牌。
我只得到一个空响应。通过 curl 执行相同的操作(我认为)可以正常工作:
curl -v -H "authorization: Bearer the_same_token_as_above" https://spreadsheets.google.com/feeds/spreadsheets/private/full
我做错了什么?
我唯一看到你缺少的是 call to start
。将以下两行添加到您的代码块对我有用(尽管 url/token 不同):
$tx = $ua->start($tx);
app->log->info($tx->res->body);
如果您有很多 API 个呼叫需要授权,那么您可能想尝试 similar to this 的方法,如下所示:
my $ua = Mojo::UserAgent->new;
$ua->on(start => sub {
my ($ua, $tx) = @_;
$tx->req->headers->authorization('Bearer <your token here>');
});
my $tx = $ua->get('<your first url here>');
app->log->info("Response body:", $tx->res->body);
my $tx = $ua->get('<your second url here>');
app->log->info("Response body:", $tx->res->body);
# etc...
这种技术的优点是每次你使用那个UserAgent
实例的get
方法时,它都会触发启动事件监听器并为你添加授权header .
我目前正在尝试完成这项工作:
my $ua = Mojo::UserAgent->new;
my $req = Mojo::Message::Request->new;
my $tx = $ua->build_tx(GET => 'https://spreadsheets.google.com/feeds/spreadsheets/private/full');
app->log->info($c->session('token'));
$tx->req->headers->authorization('Bearer ' . $c->session('token'));
其中 $c->session('token')
是我通过 Mojolicious::Plugin::OAuth2 获得的令牌。
我只得到一个空响应。通过 curl 执行相同的操作(我认为)可以正常工作:
curl -v -H "authorization: Bearer the_same_token_as_above" https://spreadsheets.google.com/feeds/spreadsheets/private/full
我做错了什么?
我唯一看到你缺少的是 call to start
。将以下两行添加到您的代码块对我有用(尽管 url/token 不同):
$tx = $ua->start($tx);
app->log->info($tx->res->body);
如果您有很多 API 个呼叫需要授权,那么您可能想尝试 similar to this 的方法,如下所示:
my $ua = Mojo::UserAgent->new;
$ua->on(start => sub {
my ($ua, $tx) = @_;
$tx->req->headers->authorization('Bearer <your token here>');
});
my $tx = $ua->get('<your first url here>');
app->log->info("Response body:", $tx->res->body);
my $tx = $ua->get('<your second url here>');
app->log->info("Response body:", $tx->res->body);
# etc...
这种技术的优点是每次你使用那个UserAgent
实例的get
方法时,它都会触发启动事件监听器并为你添加授权header .