How do I use Perl's LWP to log in to a web application?
Asked Answered
A

3

5

I would like to write a script to login to a web application and then move to other parts of the application:

use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
use Data::Dumper;

$ua = LWP::UserAgent->new(keep_alive=>1);

my $req = POST "http://example.com:5002/index.php",
[ user_name     => 'username',
  user_password => "password",
  module        => 'Users',
  action        => 'Authenticate',
  return_module => 'Users',
  return_action => 'Login',
];

my $res = $ua->request($req);
print Dumper(\$res);
if ( $res->is_success ) {
    print $res->as_string;
}

When I try this code I am not able to login to the application. The HTTP status code returned is 302 that is found, but with no data.

If I post username/password with all required things then it should return the home page of the application and keep the connection live to move other parts of the application.

Amanuensis answered 22/6, 2009 at 19:16 Comment(0)
U
15

You may be able to use WWW::Mechanize for this purpose:

Mech supports performing a sequence of page fetches including following links and submitting forms. Each fetched page is parsed and its links and forms are extracted. A link or a form can be selected, form fields can be filled and the next page can be fetched. Mech also stores a history of the URLs you've visited, which can be queried and revisited.

Undertow answered 22/6, 2009 at 19:31 Comment(0)
P
9

I'm guessing that LWP isn't following the redirect:

push @{ $ua->requests_redirectable }, 'POST';

Any reason why you're not using WWW::Mechanize?

Parturient answered 22/6, 2009 at 19:29 Comment(0)
C
1

I've used LWP to log in to plenty of web sites and do stuff with the content, so there should be no problem doing what you want. Your code looks good so far but two things I'd suggest:

  1. As mentioned, you may need to make the requests redirectable
  2. You may also need to enable cookies: $ua->cookie_jar( {} );

Hope this helps

Creuse answered 15/6, 2010 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.