Hello again.
I was trying to login to my web server protected with basic auth, and after i understood that it would be nice to automatically detect the realm so now i want to know on how to do so.
Thanks in advance.

Dani AI

Generated

Good find by — the server advertises the realm in the WWW-Authenticate header. A simple, robust pattern is: do the initial fetch, detect the 401 and the WWW-Authenticate value, extract the realm, register credentials for the host:port and retry. The example below shows a tolerant realm extraction and a retry; it also shows a preemptive Basic option to avoid the extra round trip.

use strict;
use warnings;
use URI;
use MIME::Base64;
use LWP::UserAgent;

my $ua   = LWP::UserAgent->new;
my $url  = 'http://127.0.0.1/';
my ($user, $pass) = ('admin', 'password');

my $res = $ua->get($url);

if ($res->code == 401) {
    my $www = $res->header('WWW-Authenticate') || '';
    if ($www =~ /\brealm=(?:"([^"]*)"|'([^']*)'|([^,]*))/i) {
        my $realm = $1 || $2 || $3;
        $realm =~ s/^"(.*)"$/$1/;            # strip surrounding quotes
        my $uri    = URI->new($url);
        my $netloc = $uri->host . ':' . $uri->port;
        $ua->credentials($netloc, $realm, $user => $pass);
        $res = $ua->get($url);              # retry with credentials
    }
}

To send Basic auth up front (skip the 401), set an Authorization header once:

my $auth = 'Basic ' . encode_base64("$user:$pass", '');
$ua->default_headers->header(Authorization => $auth);
my $res = $ua->get($url);

Notes and caveats: servers may return multiple WWW-Authenticate challenges (Basic, Digest); the regex above extracts the first realm-like token but Digest responses include additional parameters (nonce, qop). The realm string is server-defined and must match what the server sends, so exact matching matters for LWP::UserAgent->credentials. Never send credentials over plain HTTP in production; prefer HTTPS, read secrets from secure storage (env, .netrc via Net::Netrc, or a prompt), and handle failed auth retries gracefully. This builds on 's discovery of the WWW-Authenticate header by showing parsing, registration, retry, and a preemptive alternative.

Sorry if i didnt expleined me well.
I have the next code :

use LWP::UserAgent;
my $browser = LWP::UserAgent->new;
$browser->agent('localbot');
$browser->credentials(
'127.0.0.1:80',
'testing',#<- the $realm
'admin' => 'password');

my $response = $browser->get('http://127.0.0.1/');
if($response->status_line eq '200 OK')
{
print $response->decoded_content;
}

And i want that the $realm be detected automatically.

Ok, found the solution, i can get it with:
print $response->header("WWW-Authenticate");

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.