Perl REST client, authentication issue

我与影子孤独终老i 提交于 2019-12-12 13:18:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!