LWP::UserAgent HTTP Basic Authentication

痴心易碎 提交于 2019-12-04 03:05:33

LWP will only send the credentials for a realm if the server has told it that it's trying to access that realm. A particular user may only be able to access particular realms or have different passwords for different realms. LWP doesn't know which one to pick out of its credentials without the realm. Additionally, LWP isn't going to use the data you store in the credentials unless it's been challenged. You're not doing that.

If you supply the credentials directly by specifying the Authorization header, you do no realm checking. You can always send any header you like if you set it explicitly yourself, so it's not surprising that you see it.

You just need a better test server:

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!' );
    }

When you run your client once, there should be two requests:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!