Jeremy Smith's blog

Entry Is Labelled

Using 2-Legged OAuth with Google Apps in Perl

I found examples of working with OAuth and 2-legged access into Google Apps data, but the examples were in Python and PHP and made use of Google code libraries that hid some of the complexities. After some trial and error, I got some Perl code working with it. There were a couple of gotchas involving redirects, query parameters, and re-signing the OAuth requests; so I thought I would publish what worked for me.

use LWP::UserAgent;
use HTTP::Request::Common;
use URI;
use Net::OAuth;

sub consumer_key { 'example.com' }
sub consumer_secret { '********' }
sub username { 'user' }
sub url { 'http://www.google.com/calendar/feeds/default/allcalendars/full'; }


my $oauth_request =
        Net::OAuth->request('consumer')->new(
          consumer_key => consumer_key(),
          consumer_secret => consumer_secret(),
          request_url => url(),
          request_method => 'GET',
          signature_method => 'HMAC-SHA1',
          timestamp => time,
          nonce => nonce(),
          extra_params => {
            'xoauth_requestor_id' => username() . '@' . consumer_key(),
          },
        );


$oauth_request->sign;

my $req = HTTP::Request->new(GET => url() . '?xoauth_requestor_id='
                            . username() . '@' . consumer_key());
$req->header('Content-type' => 'application/atom+xml');
$req->header('Authorization' => $oauth_request->to_authorization_header);

my $ua = LWP::UserAgent->new;
my $oauth_response = $ua->simple_request($req);
while($oauth_response->is_redirect) {
  my $url = URI->new($oauth_response->header('Location'));
  $req->uri($url);

  my %query = $url->query_form;
  foreach my $param (keys %query) {
    $oauth_request->{extra_params}->{$param} = $query{$param};
  }

  $url->query(undef); # clear out the query parameters
  $oauth_request->{request_url} = $url;
  $oauth_request->sign; # resign
  $req->header('Authorization' => $oauth_request->to_authorization_header);

  $oauth_response = $ua->simple_request($req);
}

print $oauth_response->as_string;

sub nonce {
  my @a = ('A'..'Z', 'a'..'z', 0..9);
  my $nonce = '';
  for(0..31) {
    $nonce .= $a[rand(scalar(@a))];
  }

  $nonce;
}

Comments

  1. gravatar

    nrNHnv tnypiiwhyixh, [url=http://knglnknvqhty.com/]knglnknvqhty[/url], [link=http://ajjhohtvlccx.com/]ajjhohtvlccx[/link], http://emxoambdduhk.com/

Post a comment