newspaint

Documenting Problems That Were Difficult To Find The Answer To

Basic Authentication in Perl by Inheriting from LWP::UserAgent or WWW::Mechanize

We can easily provide HTTP basic authentication in the LWP::UserAgent and WWW::Mechanize modules by subclassing them and overriding the get_basic_credentials() method. We also provide a set_credentials() function for providing the username and password.

Note that this is a very simple override – because the get_basic_credentials() routine may discriminate between different Authentication Realms as well as URLs. The provided function in this article merely assumes you want the username/password to be provided for every webpage accessed.

package MyAgent;

use vars qw(@ISA);
@ISA = qw(LWP::UserAgent);

my ( $username, $password ) = ( undef, undef );

# method to set username and password for authentication
sub set_credentials {
  my $self = shift;
  ( $username, $password ) = @_;
}

# this routine gets called when your browser
#   would otherwise be asked to provide a
#   username and password
sub get_basic_credentials {
  my ($self, $realm, $uri) = @_;
  print( STDERR "  - providing auth to realm \"$realm\"\n" );
  return( $username, $password );
}
package MyMech;

use vars qw(@ISA);
@ISA = qw(WWW::Mechanize);

my ( $username, $password ) = ( undef, undef );

# method to set username and password for authentication
sub set_credentials {
  ( $username, $password ) = @_;
}

# this routine gets called when your browser
#   would otherwise be asked to provide a
#   username and password
sub get_basic_credentials {
  my ($self, $realm, $uri) = @_;
  print( STDERR "  - providing auth to realm \"$realm\"\n" );
  return( $username, $password );
}

Example Usage

You can use your new class where you would have otherwise used LWP::UserAgent (or WWW::Mechanize), e.g.:

package main;

my $mech = MyMech->new();
$mech->set_credentials( "administrator", "incharge" );
$mech->get( $url );
print( $mech->status . "\n" );
print( $mech->success );

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: