title: Accessing Google Calendar API with OAUTH2 via Perl
body: <p>I've been trying to authenticate with a google calendar with a service account, and not having much luck.  The following program dies during the JSON::WebToken encode call with</p>
  
  <p>RSA.xs:178: OpenSSL error: bad base64 decode at /usr/local/share/perl/5.14.2/JSON/WebToken/Crypt/RSA.pm line 19.</p>
  
  <p>When I pull out the private key and try to validate it with openssl, I get a similar error. So is Google giving me a duff key (I've double checked it) or am I doing something else wrong?</p>
  
  <pre><code>#!/usr/bin/perl
  use warnings;
  use strict;
  use JSON;
  use JSON::WebToken;
  use LWP::UserAgent;
  
  my $private_key_string = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n";
  
  my $time = time;
  
  my $jwt = JSON::WebToken-&gt;encode(
      {
          # your service account id here
          iss   =&gt; '...9ve@developer.gserviceaccount.com',
          scope =&gt; "https://www.google.com/calendar/feeds/",
          aud   =&gt; 'https://accounts.google.com/o/oauth2/token',
          exp   =&gt; $time + 3600,
          iat   =&gt; $time,
          # To access the google admin sdk with a service account
          # the service account must act on behalf of an account
          # that has admin privileges on the domain
          # Otherwise the token will be returned but API calls
          # will generate a 403
          prn =&gt; 'me@gmail.com',
      },
      $private_key_string,
      'RS256',
      { typ =&gt; 'JWT' }
  );
  
  # Now post it to google
  my $ua       = LWP::UserAgent-&gt;new();
  my $response = $ua-&gt;post(
      'https://accounts.google.com/o/oauth2/token',
      {   grant_type =&gt; encode_entities('urn:ietf:params:oauth:grant-type:jwt-bearer'),
          assertion  =&gt; $jwt
      }
  );
  
  unless ( $response-&gt;is_success() ) {
      die( $response-&gt;code, "\n", $response-&gt;content, "\n" );
  }
  </code></pre>