Skip to content

Instantly share code, notes, and snippets.

@leegee
Last active November 13, 2017 07:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leegee/0121b715c249ec3f3b6e053933781c5f to your computer and use it in GitHub Desktop.
Save leegee/0121b715c249ec3f3b6e053933781c5f to your computer and use it in GitHub Desktop.
Google REST API with Perl JSON::WebToken
use strict;
use warnings;
require JSON::XS;
require JSON::WebToken;
require LWP::UserAgent;
my $google_ua = signin_with_google(
service_account_id => $SERVICE_AC_ID,
private_key => $PRIVATE_KEY,
scopes => [
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/fusiontables',
'https://www.googleapis.com/auth/drive',
]
);
my $api_response = $google_ua->get(
'https://www.googleapis.com/fusiontables/v2/tables'
);
if ($api_response->is_success) {
die $api_response->code .' - '. $api_response->message, "\n\n", $api_response->content, "\n\n ... ";
} else {
require Data::Dumper;
warn Data::Dumper::Dumper JSON::XS::decode_json($api_response->content);
}
sub signin_with_google {
my $args = ref($_[0])? shift : {@_};
$args->{duration} ||= 60 * 10;
$args->{scopes} = ref($args->{scopes})? join(' ', @{$args->{scopes}}) : $args->{scopes};
my $time = time;
my $res = LWP::UserAgent->new()->post('https://accounts.google.com/o/oauth2/token', {
grant_type => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
assertion => JSON::WebToken->encode(
{
iss => $args->{service_account_id},
scope => $args->{scopes},
aud => 'https://accounts.google.com/o/oauth2/token',
exp => $time + $args->{duration},
iat => $time
},
$args->{private_key},
'RS256', {typ => 'JWT'}
)
});
unless ($res->is_success()) {
die $res->code .' - '. $res->content;
}
my $google_ua = LWP::UserAgent->new();
$google_ua->default_header(
Authorization => 'Bearer ' . JSON::XS::decode_json($res->content)->{access_token}
);
warn 'Ready to call API...';
return $google_ua;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment