Sunday, March 28, 2010

Twitter OAuth Login - Part 3

1. Part 1
2. Part 2

Note : As mentioned in part 2 , we will be using Elliot Haughin's twitter library for this article. Please note that library uses codeigniter framework.

So the actual coding integration is actually consist of totally three functions or actions.

1. Create a Twitter login Button.

All you need to do is this,

<a href="index.php/login/twitterLogin" >
<img style="border: 0px none ;" src="images/connenct-twitter.jpg" />

2. Create a function to handle Twitter button click

In our above code, that function or page is, 'index.php/login/twitterLogin'. So when the user will click the link, this function will be called.

This function will redirect the user to Twitter along with sending the consumer key and consumer secret key information. Now from where to get these keys ? If you remember in the last part we registered an application with Twitter, so when Twitter registers an application, it assigns the application a consumer and consumer secret . You can get this information from the application page.


Our function will look like this

function twitterLogin()
{
try
{

$consumer_key = $this->config->item('twitter_consumer_key');
$consumer_key_secret = $this->config->item('twitter_consumer_secret');

$this->load->library('twitter');
$this->twitter->oauth($consumer_key,$consumer_key_secret);
}
catch(Exception $ex)
{
log_message('error', $ex->getMessage());
$error = 'Unable to connect to Twitter, please try after a while.';
}
}
That's all! User will be redirected to Twitter where he will be asked to authorize your application. Once the user allows or denies the access, he will be redirected back to your website. This url will be the 'callback' url you provided at the time of application registration.

3. Create a function to handle User redirection from Twitter

In this function, you will know if the user allowed the access or denied. If allowed then you will talk back to Twitter to send you access token for user. You may want to store this access token in database in order to to use it for future actions like updating his twitter status from your application.

function twitterCallBack()
{
try
{

if(isset($_GET['denied']))
{
header('Location: ' . $this->config->item('base_url'));
return;
}

$consumer_key = $this->config->item('twitter_consumer_key');
$consumer_key_secret = $this->config->item('twitter_consumer_secret');

$this->load->library('session');

$tokens['access_token'] = NULL;
$tokens['access_token_secret'] = NULL;

// GET THE ACCESS TOKENS

$oauth_tokens = $this->session->userdata('twitter_oauth_tokens');

if ( $oauth_tokens !== FALSE ) $tokens = $oauth_tokens;

$this->load->library('twitter');

$auth = $this->twitter->oauth($consumer_key, $consumer_key_secret, $tokens['access_token'], $tokens['access_token_secret']);

if ( isset($auth['access_token']) && isset($auth['access_token_secret']) )
{
// SAVE THE ACCESS TOKENS

$this->session->set_userdata('twitter_oauth_tokens', $auth);

if ( isset($_GET['oauth_token']) )
{
$uri = $_SERVER['REQUEST_URI'];
$parts = explode('?', $uri);

// Now we redirect the user since we've saved their stuff!

header('Location: '.$parts[0]);
return;
}
}

header('Location: ' . $this->config->item('base_url').'index.php/dashboard');
}
catch(Exception $ex)
{
log_message('error', $ex->getMessage());

}

}
...And you are done!

Friday, March 26, 2010

Twitter OAuth Login - Part 2

The part 1 of this post can be checked here

1. First Step : Get a Twitter Account


If you already have a twitter account then you can ignore it else you need to create one at twitter.

2. Second Step : Register your application with Twitter

a. Log in to Twitter.
b. On the top menu, click 'settings'
c. On the settings page, you will see another menu, click 'connections.'
d. On the right hand, you will see a heading 'Developers' with a link to manage your application, click it.

e. You will be redirected to a page with a link to 'register new application,' click it.

f. Fill in the application registration form, it asks for some general information about your website like name and website url. Some important fields you need to fill in correctly are,
  • Call back URL - That's the page user will be redirected to once he will provide twitter his authentication details. This url will eventually be talking back to Twitter in order to get the access token for the user.
  • Application Type : Select 'browser.' 'Client' in other words desktop applications are out of the scope of this document.
  • Default Access Type : If you want to allow user to update his Twitter status right from your application then select 'Read & Write' else just 'Read.'
  • Use Twitter for login : Select it.



g. Once the form has been filled, submit it. If the application has been registered successfully, it will start appearing on Manage Applications page.

3. Third Step : Integrate it into your website

In order to integrate Twitter, you need a Twitter library with OAuth support. You may decide to write everything from scratch but hopefully you wouldn't want to reinvent the wheel. The one that I used is written by 'Elliot Haughin' and you can download it from here : http://www.haughin.com/code/twitter/

He developed it mainly for codeigniter framework but it would work just fine if used otherwise, you may just have to replace some codeigniter keywords. If you want to use a non codeigniter library then check out this one : http://github.com/abraham/twitteroauth

I would be using Elliot's library in rest of the article.

The next post will be the last in the series and would be discussing the code we need to write.

1. Part 1
2. Part 2
3. Part 3

Thursday, March 25, 2010

Twitter OAuth Login - Part 1

You must have noticed that lately a lot of sites have started to use login via Twitter and you migt already have used a screen like the following,



So that's what we will be discussing today, that's how to integrate Twitter login.

Why should we go for login via Twitter (or for that matter any other service like FaceBook)?

Login using a popular third party website is a good option both for the site and the user. User wouldn't have to go through the pain of entering all the sign up details and thus site wouldn't loose a user just because he was too lazy to fill in the sign up information. But offcourse no user wouldn't want to give their Twitter login credentials to just about any site who may end up storing your details in their database and misuse it or their database get hacked. Twitter understands it and therefore supports OAuth.

So what's OAuth and how does this address this issue?
If you're storing protected data on your users' behalf, they shouldn't be spreading their passwords around the web to get access to it. Use OAuth to give your users access to their data while protecting their account credentials.
If you want to understand the A-Z of how OAuth works, go here : http://www.oauth.net/core/1.0/

Let me give you a short summary in plain English. In order to understand how OAuth works, let's define two terminologies in terms of integrating Twitter login,

Consumer - This is the site which wants to integrate Twitter login.
Service provider - Twitter.

Here's the OAuth cycle.

1. Consumer sends a request token to Service provider.

2. Service provider grants a request token. This token is mainly to authorize the consumer using an id and secret key combination. It would be use to get Access token for user.

3. End user gets redirected to service provider's website.

4. User authorizes and gets redirected back to the consumer site

4. Consumer site requests service provider for a access token.

5. Service provider grants the token.

6. User is redirected to protected site pages.

So how could we integrate Twitter login to our website ?

Twitter is a good service but when it comes to API it's quite a pain mainly because it doesn't really have an official library, so you are left with two options: either to build one yourself or try to find a good an reliable library on the net. Twitter suggests some libraries but they aren't official. Secondly Twitter OAuth login is still a ...... beta! And beta services mean only one thing : they can change anytime! But as everybody is using it these days so I hope Twitter will not make any ground breaking changes.

So this post was to give you all the introduction. In next post we will be discussing the actual integration.

1. Part 2
2. Part 3

Codeigniter

I have some experience with cakePHP and I eventually get to play with code igniter - another php framework and I think it's just too brilliant!

It's faster, flexible and much easier than cakePHP but the best part is their detailed guide, just about everything is in there. A codeigniter site is installed as soon as you copy and paste it and writing it's hello world program hardly takes 30 seconds. Learning it is not really a dedicated job, you could learn it on the go thanks to it's extremely well written guide.

Most of the helper functions like emails engine is already there and you don't really have to install any pear library. Unlike cakePHP it is much optimized, eg. it supports persistent db connection by default while cakePHP's default option is non persistent.

So if you are into php coding, this is one framework which you must check : http://codeigniter.com/downloads/