问题
I am using Perl 5.16 with REST::Client for REST call with GET, but it shows an error 401 authentication issue. I am not clear how to resolve this issue.
Code
use REST::Client;
use JSON;
use Data::Dumper;
use MIME::Base64;
my $username = 'test';
my $password = 'test';
my $client = REST::Client->new();
$client->setHost('http://myurl');
my $headers = {
Accept => 'application/json',
Authorization => 'Full' . encode_base64($username . ':' . $password)
};
$client->GET('folder/file', $headers);
print $client->responseCode();
print $client->responseContent();
回答1:
It looks like you are doing HTTP Basic authentication. For that, you need to have your header as follows:
Authorization: Basic foobar
Where foobar
is the base64 representation of username:password
.
In Perl, that gives:
my $headers = {
Accept => 'application/json',
Authorization => 'Basic ' . encode_base64($username . ':' . $password)
# ^ note the space here
};
Note that HTTP::Headers also provides a method to set HTTP Basic authentication. Unfortunately that's not directly accepted by REST::Client.
回答2:
I faced a similar issue and found that I had to tell encode_base64 to not break up the response string e.g encode_base64($username . ':' . $password, "")
来源:https://stackoverflow.com/questions/31516238/perl-rest-client-authentication-issue