如何在PERL中调用restful Web服务时包含SSL客户端证书

时间:2016-05-02 15:35:50

标签: perl rest ssl restful-url

我试图从Linux服务器上调用一个安静的Web服务。我提供了一个.pem文件来包含它以便调用它,但我不知道在我的PERL脚本中将它添加到何处。我一直收到" 500 SSL谈判失败:"错误

我的.PEM文件被调用:

/u/data/aFolder/cert/theCert.pem

这就是我的PERL脚本

#!/opt/standard_perl/perl5881/bin/perl -w

use strict;
use warnings;
use Data::Dumper;
use LWP::UserAgent;
use HTTP::Request;
use Crypt::SSLeay;


#Validates that a url is passed via the arguements
my $global_url;
if (!defined($ARGV[0]))
{
    print "No URL passed";
    exit 400;
}else
{
    $global_url = $ARGV[0];
}

my $retry = 1;
# Retry logic, if service got a error code 500, it will
while ($retry <= 3)
{
    # Connects to service, if response was sucessfull then it prints he content
    # and exits the response code, else, retry 3 more times if the code was 500
    my $response = connectToService($global_url);
    if ($response->is_success)
        {
            print $response->content() . "\n";
            exit($response->code);
        }else
        {
            if ($response->code == 500 && $retry < 3)
            {
                $retry++;
                next;
            }
            print $response->status_line() ."\n";
            exit($response->code);
        }
}
######################################
# Passes the url and calls the service
######################################
sub connectToService
{
    my $url = shift;

    my $agent = LWP::UserAgent->new;
    my $request = HTTP::Request->new(GET => $url);
    $request->header('Cache-Control' => 'no-cache');
    $request->header('accept' => 'application/json');
    return $agent->request($request);
}

目前我的结果是:

username@theServer:/u/is/bin $ serviceCall.pl https://thewebServiceURL.com:3122/services/v1/quantity/foo/bar/info/11111
500 SSL negotiation failed:
username@theServer:/u/is/bin $

非常感谢任何帮助

1 个答案:

答案 0 :(得分:0)

使用客户端证书的方式取决于LWP的版本和基础SSL库。使用LWP版本6.0(2011年发布)默认情况下使用IO::Socket::SSL作为底层库,并在那里使用ssl_opts提供证书:

$agent->ssl_opts(
    SSL_cert_file => 'cert.pem',
    SSL_key_file => 'key.pem'
);

使用旧版本的LWP Crypt::SSLeay代替,然后您需要使用环境变量指定证书:

$ENV{HTTPS_CERT_FILE} = 'cert.pem';
$ENV{HTTPS_KEY_FILE}  = 'key.pem';

看起来你正在尝试强制使用Crypt :: SSLeay但我实际上建议使用IO :: Socket :: SSL,因为它是更现代的SSL库,正确验证证书(与Crypt相反: :SSLeay),支持SNI等。