user1700494
user1700494

Reputation: 211

Get access token in perl

There is a working sample of getting token in bash

response=$(curl  --fail --silent --insecure --data "username=test&password=test" \
--header "Authorization: Basic Y2xvdWQtYmVzcG9rZTo=" \
-X POST "https://lab7.local:8071/auth/token?grant_type=password")
token=`echo "$response" | awk '/access_token/{print $NF}' |sed 's/\"//g'`
echo $token

I'm trying to translate it in perl, but getting code 400

#!/usr/bin/env perl
use strict;
use warnings;
use HTTP::Request;
use LWP::UserAgent;
use LWP::Simple;
use JSON::XS;
use Try::Tiny;

my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => "https://lab7.local:8071/auth/token?grant_type=password");
my $post_data = "username=test&password=test";
$req->content($post_data);
my $resp = $ua->request($req);
if ($resp->is_success) {
    my $mess = $resp->decoded_content;
    print "$mess\n";
} else {
     my $code = $resp->code;
     print $code;
}

Upvotes: 0

Views: 3784

Answers (2)

Sobrique
Sobrique

Reputation: 53478

You're adding a basic auth header, with a username. That string is just the base 64 encoded equivalent.

So you should probably include this in your LWP:

$req -> authorization_basic ( 'cloud-bespoke' ); 

And it should work.

Upvotes: 0

Dave Cross
Dave Cross

Reputation: 69224

Your curl version is sending an Authentication header that is missing from the Perl version. You should add that.

$req->header(Authorization => 'Basic Y2xvdWQtYmVzcG9rZTo=');

Upvotes: 2

Related Questions