r/perl • • Jun 25 '15

LWP::UserAgent and Basic Authentication

http://perlmaven.com/lwp-useragent-and-basic-authentication
0 Upvotes

2 comments sorted by

1

u/Farow Jun 26 '15

Feels kinda meh. I recently wrote some script using reddit's API and I found what I think is a somewhat better solution:

use v5.20;
use LWP::UserAgent;
use HTTP::Request::Common;

my $ua = LWP::UserAgent->new();
my $request = GET 'https://pause.perl.org/pause/authenquery';

$request->authorization_basic('user', 'pass');

my $response = $ua->request($request);
say $response->as_string();

I'm not expert in the field but this seems a bit neater than rewriting other methods.

0

u/joelberger 🐪 cpan author Jun 26 '15

Mojo::UserAgent makes it even easier

use Mojo::Base -strict;                                                                      
use Mojo::UserAgent;                                                                         
                                                                                         
my $ua = Mojo::UserAgent->new;                                                               
                                                                                         
my $tx = $ua->get('https://USERNAME:[email protected]/pause/authenquery');             
# OR if your username has an @                                                               
my $url = Mojo::URL->new('https://pause.perl.org/pause/authenquery')->userinfo('[email protected]:PASSWORD');
my $tx = $ua->get($url);                                                                     
                                                                                         
print $tx->res->text;