Limbic~Region has asked for the wisdom of the Perl Monks concerning the following question:

All,
I have already resolved this issue, but I am wondering if anyone has any ideas on why it is necessary and if there is a better way. Here is the situation:
  1. $mech->get($url); # Page fetched is http://foo.com
  2. $mech->credentials($user, $pass); # Basic Authentication
  3. $mech->submit(); # Goes to https://foo.com (basic authentication) then redirects back to http://foo.com

Now, I tried every incantation I could with $mech->credentials() and when I called it but every single time it would spit out an error saying POST failed because https://foo.com required authentication. Here is how I resolved it:

$mech->default_header(Authorization => 'Basic ' . encode_base64($user +. ':' . $pass)); $mech->get($url); $mech->submit();

Does anyone know why this was necessary and does anyone have a better solution (preferrably using credentials()?

Cheers - L~R

Replies are listed 'Best First'.
Re: Better Solution To WWW::Mechanize Basic Authentication
by MidLifeXis (Monsignor) on Oct 19, 2009 at 14:58 UTC
      MidLifeXis,
      Mech inherits from LWP::UA.

      Yes, I know. That's how I was able to solve the problem - using the inherited default_header() method. I still don't see how your suggestion helps.

      My understanding after RTFM is that this is just a way to get user name and password not set it. It just uses previously stored information from the credentials() method - which I indicate didn't work for me.

      Can you please show me an example of how you think this might help me?

      Cheers - L~R

        Note: vastly simplified.

        package MyUA; use base 'LWP::UserAgent'; { my $user; my $pass; sub set_creds { $user = shift; $pass = shift; } sub get_basic_credentials { ($user, $pass) } }

        get_basic_credentials() is called by the GET/POST/FOO methods when challenged (perhaps more often, you may need to verify this). I use it to read passwords from a config file, prompt from a terminal w/o echoing, and other times that I need to access restricted sites.

        Update: credentials(), afaict, takes 4 parameters, not two. Perhaps that is the root of the reason it isn't working. Reached for my favorite hammer when a screwdriver was already provided.

        Update 2: Per almut in Re^4: Better Solution To WWW::Mechanize Basic Authentication, I stand corrected. Two parameter version is quite correct.

        --MidLifeXis