【问题标题】:How can I make a request authorized with Oauth with Mojo::UserAgent?如何使用 Mojo::UserAgent 发出 Oauth 授权的请求?
【发布时间】:2015-12-09 19:47:36
【问题描述】:

我目前正在努力完成这项工作:

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

我做错了什么?

【问题讨论】:

    标签: perl oauth mojolicious mojolicious-lite


    【解决方案1】:

    我看到你唯一缺少的是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 方法时,它都会触发启动事件侦听器并为您添加授权标头。

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 1970-01-01
      • 2014-09-23
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2016-09-18
      • 1970-01-01
      相关资源
      最近更新 更多