sim*_*one 2 perl oauth mojolicious mojolicious-lite
我目前正在努力实现这项工作:
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'));
Run Code Online (Sandbox Code Playgroud)
我通过Mojolicious::Plugin::OAuth2$c->session('token')获得的令牌在哪里。
我只得到空的回复。通过curl 做同样的事情(我认为)也可以:
curl -v -H "authorization: Bearer the_same_token_as_above" https://spreadsheets.google.com/feeds/spreadsheets/private/full
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我发现您唯一缺少的是对 的调用start。将以下两行添加到代码块对我有用(尽管使用不同的网址/令牌):
$tx = $ua->start($tx);
app->log->info($tx->res->body);
Run Code Online (Sandbox Code Playgroud)
如果您有很多 API 调用需要授权,那么您可能需要尝试类似于此的方法,如下所示:
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...
Run Code Online (Sandbox Code Playgroud)
这种技术的优点是,每次您使用get该UserAgent实例的方法时,它都会触发启动事件侦听器并为您添加授权标头。