在WWW :: Mechanize中设置基本身份验证凭据 [英] Setting basic authentication credentials in WWW::Mechanize

查看:93
本文介绍了在WWW :: Mechanize中设置基本身份验证凭据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WWW :: Mechanize 中使用基本身份验证时遇到问题.我正在尝试连接到 Streak API ,该文档的状态如下:

I'm having trouble using basic authentication in WWW::Mechanize. I'm trying to connect to the Streak API, the documentation for which states:

Streak使用HTTP基本身份验证使用您的API密钥对每个请求进行签名.只需将请求的用户名设置为API密钥即可.密码字段将被忽略.所有请求都必须通过HTTPS进行,因为HTTP请求将被忽略.

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.

这是一个示例请求:

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

我可以使用curl以这种方式成功访问API.但是,我无法使用WWW :: Mechanize成功进行身份验证.这就是我所拥有的:

I can successfully access the API using curl in this fashion. However, I'm not able to authenticate successfully using WWW::Mechanize. Here's what I've got:

#!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中运行,如果与它有任何关系.

The authentication isn't even being attempted. Can anyone suggest why that may be the case, and what I could do to fix it? This code is running in Strawberry Perl 5.24.0.1, if that may have anything to do with it.

[已编辑,包括来自simbabque的检查请求对象的建议.]

推荐答案

我发现了问题.

按照 Perl Maven上的帖子(如何找出网址和领域?"),那么当您尝试连接到该领域时,该API不会发送证书挑战,即指定领域.它只是给您一条错误消息,指出需要基本身份验证. LWP :: UserAgent当时不知道要执行其他任何操作.

Following the technique in this post on Perl Maven ("How to find out the URL and realm?"), it turns out that the API doesn't send a challenge for credentials, specifying a realm, when you try connecting to it. It just gives you an error message stating that basic authentication is required. LWP::UserAgent doesn't know to do anything else at that point.

因此,我从simbabque建议检查的成功curl请求中复制了身份验证标头,并在用户代理对象上手动设置了该标头:

So, I copied the authentication header from the successful curl request that simbabque suggested examining, and manually set that on the user-agent object:

$ua->default_header('Authorization' => 'Basic [Base64-encoded string here]');

现在可以使用了.快乐的时光.

Now it works. Happy times.

这篇关于在WWW :: Mechanize中设置基本身份验证凭据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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