Monday, February 14, 2011

How to exchange a requested TOKEN for an access TOKEN from Twitter in PERL

Finally, we're here at the last part of OAuth process, exchanging the requested token for an access token. I assume you were able to follow my last 2 posts below.
To get an access token, we need the OAuth Token, and Verifier from the previous post.

Just follow the simple steps below to gain an access token which we will use to access Twitter API in users behalf. This is likely the same when requesting a token, the only difference are the parameters we pass on.

1. Install all the libraries you need.
  • LWP::UserAgent
  • HTTP::Cookies
  • Digest::MD5
  • Digest::SHA
  • POSIX

2. Initialize the libraries

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);

my $lwpua = LWP::UserAgent->new;

3. Setup the UserAgent and HTTP header with the name "Authorization" equal to "OAuth".

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

4. Build the signature base and signing key. Please take note that some parameters should be URL Encoded, see the post for the PERL function that you can use - URLENCODE sub function in PERL.

You need the consumer key and secret which was generated by Twitter upon registration.

You also need the Oauth Token and Verifier which you get when authorizing the requested token.

To generate NONCE, we use Digest::MD5::md5_base64() passing the localtime(). We do it twice to make it much UNIQUE.

Timestamp was generated by using POSIX::strftime() with date format UNIXTIME as "%s".

# build signature base
my $strToken = "<your oauth token>";
my $strVerifier = "<your oauth verifier>";

my $post_url = "https://api.twitter.com/oauth/access_token";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);

my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_verifier=$strVerifier&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

5. Generate the OAuth Signature using HMAC-SHA1 method.

my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

6. Post an OAuth request with all the parameters you passed on step #4.

my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_verifier' => $strVerifier,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

7. Get the return value: oauth_token, oauth_token_secret, user_id, and screen_name

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&user_id=(.*?)&screen_name=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $user_id = $3;
my $screen_name = $4;


Hope you like it! Please see the complete code below. Thank you for reading.

#!/usr/bin/perl

require LWP::UserAgent;

use strict;
use warnings;

use HTTP::Cookies;

use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA qw(sha1 sha1_hex sha1_base64 hmac_sha1 hmac_sha1_hex hmac_sha1_base64);

use POSIX qw(strftime);


my $lwpua = LWP::UserAgent->new;

my $uagent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
my @header = ('Referer' => 'https://api.twitter.com/',
             'User-Agent' => $uagent,
             'Authorization' => 'OAuth');

# build signature base
my $strToken = "<your oauth token>";
my $strVerifier = "<your oauth verifier>";

my $post_url = "https://api.twitter.com/oauth/access_token";
my $nonce = md5_base64(localtime()).md5_base64(localtime());
my $timestamp = strftime('%s', localtime);
my $method = "HMAC-SHA1";
my $version = "1.0";
my $consumer_key = "<your consumer key generated upon registration>";
my $consumer_secret = "<your consumer secret generated upon registration>";

my $post_urlenc = &urlencode($post_url);
my $oauth_data = "oauth_consumer_key=$consumer_key&oauth_nonce=$nonce&oauth_signature_method=$method&oauth_timestamp=$timestamp&oauth_token=$strToken&oauth_verifier=$strVerifier&oauth_version=$version";
my $oauth_dataenc = &urlencode($oauth_data);

my $sign_base = "POST&".$post_urlenc."&".$oauth_dataenc;
my $sign_key = $consumer_secret."&";

  # oauth signature
my $oauth_sign = hmac_sha1_base64($sign_base, $sign_key)."=";

# post oauth request
my $response = $lwpua->post($post_url,
                        ['oauth_token' => $strToken,
                         'oauth_verifier' => $strVerifier,
                         'oauth_consumer_key' => $consumer_key,
                         'oauth_nonce' => $nonce,
                         'oauth_signature_method' => $method,
                         'oauth_signature' => $oauth_sign,
                         'oauth_timestamp' => $timestamp,
                         'oauth_version' => $version], @header);
my $form_data = $response->content;

$form_data =~ s/\n//g;
$form_data =~ /^oauth_token=(.*?)&oauth_token_secret=(.*?)&user_id=(.*?)&screen_name=(.*?)\s*$/gi;

my $oauth_token = $1;
my $oauth_secret = $2;
my $user_id = $3;
my $screen_name = $4;

print "$oauth_token|$oauth_secret|$user_id|$screen_name\n";
print "done!";


sub urlencode
{
  my ($url) = @_;

  $url =~ s/([^A-Za-z0-9_.-])/sprintf("%%%02X", ord($1))/seg;
  return $url;
}



1;

No comments:

Post a Comment

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.