Perl LWP::UserAgent HTTP基本身份验证
我尝试运行这个perl5程序:Perl LWP::UserAgent HTTP基本身份验证,perl,lwp,lwp-useragent,Perl,Lwp,Lwp Useragent,我尝试运行这个perl5程序: #!/usr/bin/env perl use strict; use warnings;
#!/usr/bin/env perl
use strict;
use warnings;
use LWP;
my $ua = LWP::UserAgent->new('Mozilla');
$ua->credentials("test.server.com:39272", "realm-name", 'user_name', 'some_pass');
my $res = $ua->get('http://test.server.com:39272/');
print $res->content;
另一方面,我有HTTP::Daemon:
#!/usr/bin/env perl
use strict;
use warnings;
use HTTP::Daemon;
my $hd = HTTP::Daemon->new or die;
print "Contact URL: ", $hd->url, "\n";
while (my $hc = $hd->accept) {
while (my $hr = $hc->get_request) {
if ($hr->method eq 'GET') {
print $hr->as_string, "\n";
}
}
$hc->close;
undef($hc);
}
它只是打印:
Contact URL: http://test.server.com:39272/
GET / HTTP/1.1
Connection: TE, close
Host: test.server.com:39272
TE: deflate,gzip;q=0.3
User-Agent: libwww-perl/6.03
所以我看到LWP::UserAgent不发送HTTP基本身份验证,但我不知道为什么
我在这个网站上看到了一些帖子,但是他们有相同的基本代码,而且没有
工作
如果我使用HTTP::Request,那么它可以工作:
my $req = GET 'http://test.server.com:39272/';
$req->authorization_basic('my_id', 'my_pass');
my $res = $ua->request($req);
产出:
GET / HTTP/1.1
Connection: TE, close
Authorization: Basic bXlfaWQ6bXlfcGFzcw==
Host: test.server.com:39272
TE: deflate,gzip;q=0.3
User-Agent: libwww-perl/6.03
我以前做错什么了吗?LWP只会在服务器告诉它试图访问某个领域时发送该领域的凭据。特定用户可能只能访问特定领域,或者对不同领域拥有不同的密码。LWP不知道在没有域的情况下从其凭证中选择哪一个。此外,LWP不会使用您存储在凭据中的数据,除非它受到质疑。你没那么做 如果通过指定
授权
头直接提供凭据,则不进行领域检查。如果您自己显式地设置了任何标题,则始终可以发送您喜欢的任何标题,因此看到它也就不足为奇了
您只需要一个更好的测试服务器:
use strict;
use warnings;
use HTTP::Daemon;
use HTTP::Status;
my $server = HTTP::Daemon->new or die;
print "Contact URL: ", $server->url, "\n";
while (my $connection = $server->accept) {
while (my $request = $connection->get_request) {
print $request->as_string;
unless( $request->header( 'Authorization' ) ) {
$connection->send_response( make_challenge() )
}
else {
$connection->send_response( make_response() )
}
}
$connection->close;
}
sub make_challenge {
my $response = HTTP::Response->new(
401 => 'Authorization Required',
[ 'WWW-Authenticate' => 'Basic realm="Buster"' ],
);
}
sub make_response {
my $response = HTTP::Response->new(
200 => 'Huzzah!',
[ 'Content-type' => 'text/plain' ],
);
$response->message( 'Huzzah!' );
}
当您运行一次客户端时,应该有两个请求:
GET / HTTP/1.1
Connection: TE, close
Host: macpro.local:52902
TE: deflate,gzip;q=0.3
User-Agent: libwww-perl/6.02
GET / HTTP/1.1
Connection: TE, close
Authorization: Basic dXNlcl9uYW1lOnNvbWVfcGFzcw==
Host: macpro.local:52902
TE: deflate,gzip;q=0.3
User-Agent: libwww-perl/6.02
您是否收到401请求基本身份验证的响应?你把王国弄对了吗?显示请求-响应链,而不仅仅是请求。我为请求和响应添加了代码。我得到了401的回复。我不了解领域问题,我不明白这有多重要。我现在知道,我需要返回WWW-Authenticate:Basic realm=“Secure Area”,然后LWP::UserAgent将工作,对吗?@XoR,是的,您的服务器必须返回一个
401
状态,请求基本身份验证(使用正确的领域名称),LWP才会发送身份验证凭据。啊哈,@friedo,现在我知道了,谢谢:)