iguanodon has asked for the wisdom of the Perl Monks concerning the following question:

I recently read the perl.com article on WWW::Mechanize and it seems pretty cool. But I haven't been able to use it against pages that require basic authentication. I tried grabbing the HTTP::Request object returned by the req() method and calling authorization_basic() on it:
my $agent = WWW::Mechanize->new(); $agent->get("http://my.server.com/"); my $req = $agent->req(); $req->authorization_basic($user, $pass); $agent->follow("Some Link"); print $agent->content();
But I just get a 401 error. $user and $pass are correct, I'm logging in successfully in another script that uses 'regular' LWP.

The docs for WWW::Mechanize don't mention anything about authentication, has anyone done this?

iguanodon

Replies are listed 'Best First'.
Re: WWW::Mechanize and basic authentication
by adrianh (Chancellor) on Jan 29, 2003 at 13:12 UTC

    WWW::Mechanize is a subclass of LWP::UserAgent - so can use all of its methods.

    You want to do something like:

    my $agent = WWW::Mechanize->new(); $agent->credentials($uri->host_port, "TheRealm", "user", "pass");

    See LWP::UserAgent for details on credentials.

      That works, thanks a bunch.

      I need to understand how the credentials method of LWP::UserAgent differs from the authorization_basic method of HTTP::Request. I'm guessing that under the hood they're doing the same thing, so was my code not working because I'm passing the credentials too late in the process?

        It doesn't work because the get and follow methods create a new HTTP::Request object every time.

        req returns the HTTP::Request that was used in the last request, not the one that will be used in the next - so yes, a little late in the process :-)