在 WWW::Mechanize 中设置基本身份验证凭据

Setting basic authentication credentials in WWW::Mechanize

我在 WWW::Mechanize. I'm trying to connect to the Streak API 中使用基本身份验证时遇到问题,文档指出:

Streak uses HTTP Basic Auth to sign each request with your API key. Simply set the username of the request to the API key. The password field is ignored. All requests must be made over HTTPS as HTTP requests will be ignored.

Here's a sample request:

curl https://www.streak.com/api/v1/pipelines -u YOUR_API_KEY:

我可以使用 curl 以这种方式成功访问 API。但是,我无法使用 WWW::Mechanize 成功进行身份验证。这是我得到的:

#!perl

use warnings;
use strict;
use feature 'say';

use WWW::Mechanize;

my $api = 'https://www.streak.com/api/v1/';

my $mech = WWW::Mechanize->new( autocheck => 0 ); # don't die on errors

$mech->credentials('my API key here', '');

$mech->get($api . 'pipelines');

say $mech->response->status_line;
say $mech->res->request->as_string;

运行 我的代码得到:

401 Unauthorized
GET https://www.streak.com/api/v1/pipelines
Accept-Encoding: gzip
User-Agent: WWW-Mechanize/1.83

甚至没有尝试进行身份验证。任何人都可以建议为什么会这样,以及我可以做些什么来解决它?此代码是 Strawberry Perl 5.24.0.1 中的 运行,如果这可能与它有关。

[编辑以包含来自 simbabque 的检查请求对象的建议。]

我发现了问题。

按照 this post on Perl Maven ("How to find out the URL and realm?") 中的技术,当您尝试连接到它。它只是给你一条错误消息,说明需要基本身份验证。 LWP::UserAgent 那时不知道该做什么。

因此,我从 simbabque 建议检查的成功 curl 请求中复制了身份验证 header,并在 user-agent object:

上手动设置了它
$ua->default_header('Authorization' => 'Basic [Base64-encoded string here]');

现在可以了。快乐时光。