[英]LWP::UserAgent HTTP Basic Authentication
我試着運行這個perl5程序:
#!/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 ::守護進程:
#!/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 Basic身份驗證,但我不知道為什么。
我在這個網站上看過一些帖子,但是他們有相同的基本代碼,但它不起作用......
如果我使用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不會使用您在憑證中存儲的數據,除非它受到質疑。 你不是那樣做的。
如果通過指定Authorization
標頭直接提供憑據,則不進行領域檢查。 如果你自己明確地設置它,你總是可以發送你喜歡的任何標題,所以你看到它並不奇怪。
你只需要一個更好的測試服務器:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.