How to implement basic authentication in HTTP request with Perl?
Question
How to implement basic authentication in HTTP request with Perl?
Implementing Basic Authentication in an HTTP request using Perl is straightforward and can be done with core modules like LWP::UserAgent, which provides a high-level HTTP client. Basic Authentication requires sending a header with the username and password encoded in Base64 format.
Here’s a step-by-step explanation:
- Basic Authentication sends an HTTP header named
Authorizationwith a value ofBasic <credentials>, where<credentials>is the Base64 encoding ofusername:password. - In Perl, the
MIME::Base64core module can encode strings to Base64. LWP::UserAgent(part of libwww-perl) is the most common and convenient module for HTTP client requests.- You construct the authorization header manually or use LWP’s built-in support for basic authentication.
Example: Basic Authentication via HTTP Header
The following runnable example shows how to perform an HTTP GET request with Basic Authentication, explicitly setting the header. This example uses only core or widely distributed modules and prints the response status and content.
use strict;
use warnings;
use LWP::UserAgent;
use MIME::Base64;
# Replace these with your credentials and URL
my $username = 'myuser';
my $password = 'mypassword';
my $url = 'http://httpbin.org/basic-auth/myuser/mypassword';
# Create user agent object
my $ua = LWP::UserAgent->new;
# Encode credentials
my $credentials = encode_base64("$username:$password", '');
# Create request
use HTTP::Request;
my $req = HTTP::Request->new(GET => $url);
# Add Authorization header
$req->header('Authorization' => "Basic $credentials");
# Send request
my $res = $ua->request($req);
# Print response status and content
print "Response status: " . $res->status_line . "\n";
print "Response content:\n" . $res->decoded_content . "\n";
Explanation of key concepts:
encode_base64($string, '')encodes the string to Base64 without the trailing newline, which is important for HTTP headers.LWP::UserAgentprovides an easy interface to send HTTP requests.- HTTP headers are set on
HTTP::Requestobjects. TheAuthorizationheader is critical for Basic Auth. - Perl sigils (
$,@,%) denote scalar, array, and hash variables respectively, used here for scalars.
Alternate approach: Using LWP::UserAgent’s credentials method
LWP::UserAgent supports setting credentials directly:
$ua->credentials('host:port', 'realm', $username, $password);
This is less common for ad-hoc requests or unknown realms but can be more convenient for persistent agents.
Common pitfalls:
- Forgetting to remove the newline in Base64 encoding causes authentication failures.
- Using HTTPS for Basic Auth is strongly recommended since the credentials are only Base64 encoded, not encrypted.
- Ensure that the URL matches the server’s expected authentication endpoint and realm.
Summary
To implement Basic Authentication in Perl HTTP requests, the easiest approach is to add an Authorization header with the Base64-encoded credentials using LWP::UserAgent and MIME::Base64. This technique works well for any HTTP method and is supported widely in Perl 5.8 and later.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 706ms
Response status: 200 OK
Response content:
{
"authenticated": true,
"user": "myuser"
}
(empty)