VSe
VSe

Reputation: 929

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();

Upvotes: 3

Views: 8824

Answers (2)

Androidia
Androidia

Reputation: 1

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, "")

Upvotes: 0

simbabque
simbabque

Reputation: 54333

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.

Upvotes: 5

Related Questions