Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl REST client, authentication issue

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();
like image 434
VSr Avatar asked Nov 29 '25 23:11

VSr


1 Answers

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.

like image 123
simbabque Avatar answered Dec 01 '25 14:12

simbabque