Twitter Development: Using OAuth to Authenticate Against the Twitter API: Walkthroughs

 

This article is excerpted from Chapter 6: Basic Authentication and OAuth of the Wrox book, Professional Twitter Development: With Examples in .NET 3.5, by Daniel Crenna, and is reused by permission of the publisher. This may not be reused without publisher permission.
 
Twitter Development: Using OAuth to Authenticate Against the Twitter API: Walkthroughs
 
The best way to exercise your awareness of OAuth is to use it to authenticate against the Twitter API. You have familiarized yourself with the workflow and are capable of using the tools described earlier to authorize your applications. Now you can use OAuth with an authorized Twitter account to call API methods.
 
Setting Up Your Twitter Application to Use OAuth
 
The first step to using OAuth with Twitter is to configure your application, the process that will assign you a consumer key and consumer secret, and allow you to describe your application to others; its icon, what it does, and what access privileges it requires from authorizing users. This process begins when you log in to your Twitter account and access the Connections tab on your Settings page, as Figure 6-4 illustrates.
 

 
Figure 6-4       
 
Every Twitter user has a similar page which provides them with a list of all third-party Twitter applications that are authorized to use the user’s account; hopefully yours is among them. On the right-hand sidebar, however, you will have the option of accessing a developer page to configure your own OAuth application. Figure 6-5 provides that page.
 
Figure 6-5       
 
The configuration page allows you to provide some useful marketing information about your application, but it also serves as a portal for setting OAuth credentials for use in your application. After you save your application information, you will see as shown in Figure 6-6, which displays your newly provisioned application’s OAuth credentials for use in your authentication workflow. You can also reset your consumer key and secret if necessary.
 
Figure 6-6      
 
Authenticating an ASP.NET Web Application
 
Because OAuth authorization takes place online, Twitter applications you build as .NET web applications will benefit from a seamless workflow that moves from your site, to Twitter, and back again. The major difference between console and web applications on Twitter’s side is the need to provide a callback URL with a web application. When the user has accepted or denied access to your application, Twitter will redirect the user to the URL you provided when configuring your application for web use. Figure 6-7 is an example callback URL.
 
Figure 6-7       
 
Now that a callback URL is in place and after a user authorizes your application, your specified page will receive a request from Twitter. It will provide the request token needed to exchange for an access token provided in the query parameters, which you can parse out and use in your OAuth utility class. Because providing an explicit callback URL does not permit including localhost or a non-standard port in the URL description, you will need to deploy your application to a publically accessible URL during your development phase, or modify your machine’s HOSTS file to redirect any traffic to the callback URL’s domain to your localhost. The HOSTS file for the previous callback URL might look like this:
 
# Copyright (c) 1993-2006 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a ‘#’ symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host
            
127.0.0.1      localhost
::1            localhost
myapp.com      localhost
 
The following listing demonstrates an ASPX page that will look for this token on an incoming request, and if it is not found, will fetch a request token and send the user to Twitter’s authorization page. If the token exists, your application will know this is the third step in the workflow, and can exchange the provided token for an access token. When you have the access token, depending on your application’s needs, you may want to save it to a session or to your database to avoid the OAuth process in the future.
 
using System;
using System.Configuration;
using System.Web;
using OAuthLibrary;
            
namespace OAuthWalkthroughWebForms
{
    public partial class _Default : System.Web.UI.Page
    {
        private const string RequestUrl =
            “http://twitter.com/oauth/request_token”;
            
        private const string AccessUrl =
            “http://twitter.com/oauth/access_token”;
            
        private const string AuthorizeUrl =
            “http://twitter.com/oauth/authorize?oauth_token={0}”;
            
        protected void OnLoad(object sender, EventArgs e)
        {
            // add these to web.config or your preferred location
            var consumerKey = ConfigurationManager.AppSettings[“consumerKey”];
            var consumerSecret = ConfigurationManager.AppSettings[“consumerSecret”];
            
           // look for an access token in the callback
            var requestToken = Request.QueryString[“oauth_token”];
            if (requestToken == null)
            {
                requestToken = OAuth.GetRequestToken(RequestUrl,
                                                     consumerKey,
                                                     consumerSecret);
                var collection = HttpUtility.ParseQueryString(requestToken);
                var authorizeUrl = String.Format(AuthorizeUrl,
                                                 collection[0]);
            
                Response.Redirect(authorizeUrl);
            }
            else
            {
                // oauth is complete and callback is returning
                // the possibly authorized request token
                var collection = HttpUtility.ParseQueryString(requestToken);
            
                // obtain access token
                var accessToken = OAuth.GetAccessToken(AccessUrl,
                                                       consumerKey,
                                                       consumerSecret,
                                                       collection[0],
                                                       collection[1]);
                collection = HttpUtility.ParseQueryString(accessToken);
            
                // make a Twitter request with the access token and secret
                var url = “http://twitter.com/account/verify_credentials.xml”;
                var verify = OAuth.GetProtectedResource(url,
                                                        “GET”,
                                                        consumerKey,
                                                        consumerSecret,
                                                        collection[0],
                                                        collection[1]);
            }
        }
    }
}
 
Your understanding of OAuth and a set of useful utility methods are all that is necessary to build OAuth support into an ASP.NET web application. Setting up OAuth for a desktop, console, or mobile application is a similar process with some important differences.
 
Authenticating a Desktop, Console, or Mobile Application
 
The loudest complaints around the adoption of and experience using OAuth is from those developing desktop, console, and mobile applications. Because user authorization is explicit and enabled via Twitter’s own site, and because Twitter’s terms of service (and good manners) prohibit scraping or presenting the site in IFRAMEs, these types of applications require that you redirect the user to a web browser to authorize the application. This workflow is confusing, requires a browser, and forces the user to understand that he needs to return to your application after the authorization phase is complete to use your application. The problem is compounded with mobile applications where the browser experience may interrupt the application or cause additional steps for the user to return to your application. For example, using OAuth with an iPhone application would require you to navigate away from the application to a new browser page, authorize the application, close the browser, and then reopen the application to continue the process—clumsy for the user and troublesome for the developer who has to manage the state of that process. Essentially, a mobile application on any platform is truly a desktop client application for the purposes of engaging in an OAuth workflow that must jump from a browser to a client and back again. Here is the code to write a simple console application using Twitter and OAuth.
 
using System;
using System.Diagnostics;
using System.Web;
using OAuthLibrary;
using OAuthWalkthroughConsole.Properties;
            
namespace OAuthWalkthroughConsole
{
    class Program
    {
        private const string RequestUrl =
            “http://twitter.com/oauth/request_token”;
            
        private const string AccessUrl =
            “http://twitter.com/oauth/access_token”;
            
        private const string AuthorizeUrl =
            “http://twitter.com/oauth/authorize?oauth_token={0}”;
            
        static void Main()
        {
            Console.WriteLine(“Welcome to the OAuth Console Walkthrough”);
            Console.WriteLine();
            
            // you can get these from app.config or another source
            var consumerKey = Settings.Default.ConsumerKey;
            var consumerSecret = Settings.Default.ConsumerSecret;
            
            // get an unauthorized request token
            var requestToken = OAuth.GetRequestToken(RequestUrl,
                                                     consumerKey,
                                                     consumerSecret);
            var collection = HttpUtility.ParseQueryString(requestToken);
            
            // send the user to the authorization site out of band
            var authorizationUrl = String.Format(AuthorizeUrl, collection[0]);
            Process.Start(authorizationUrl);
            
            // wait for the user to return to the site
            Console.WriteLine(
                “Press any key to continue after “ +
                “authorizing this application…”);
            Console.ReadKey();
             
            // exchange the request token for an access token
            var accessToken = OAuth.GetAccessToken(AccessUrl,
                                                   consumerKey,
                                                   consumerSecret,
                                                   collection[0],
                                                   collection[1]);
            collection = HttpUtility.ParseQueryString(accessToken);
            
            // access a protected API call on Twitter
            var query = “http://twitter.com/statuses/user_timeline.xml”;
            
            var userTimeline = OAuth.GetProtectedResource(query,
                                                          “GET”,
                                                          consumerKey,
                                                          consumerSecret,
                                                          collection[0],
                                                          collection[1]);
            
            Console.WriteLine(userTimeline);
            Console.WriteLine();
            
            Console.WriteLine(“Press any key to exit the walkthrough.”);
            Console.ReadKey();
        }
    }
}
 
Remember that with non-browser applications, you need to identify your OAuth application as a Client rather than a Browser application to prevent Twitter from sending your users to a callback URL, though you may desire using a callback page to provide more direction for your users to return to your application. Figure 6-8 demonstrates how the user must authorize your application’s privileges while the application itself waits around for the event to occur.
 
Figure 6-8      
 
Now that you can use OAuth authentication effectively with both browser and client-based applications, you will learn a few takeaways for how to improve the client-based user experience when users are left up to their own devices to authorize and return to your application.
 
Improving the User Authorization Experience for Desktop Applications
 
Historically, sending your users on an errand without clear direction and helpful suggestions results in losing that user whether to distraction or frustration. OAuth, although an effective safeguard for your user’s data, does not lend itself to a seamless user experience for non-browser–based applications. Fortunately, Google has spent a great deal of time researching the implications of desktop applications using OAuth for federated login strategies. Even though you can’t get around the need to switch contexts, you can help the user along with a careful choice of words on your client’s sign-in page. Figure 6-9 shows a mock up for a login UI, based loosely on Google’s federated login, and might help clarify the intent of your application to your users.
 
Figure 6-9
 
With this login design, the following things are clear to the user:
  • The user needs a Twitter account to move forward with your application,
  • If the user does not have a Twitter account, your application will assist the user with setting up a new account, likely redirecting them to Twitter’s signup page,
  • The user has no opportunity to enter a password directly with your application, but you will assist them with entering their password on Twitter, and finally,
  • The user is able to save their access token using your desktop application, so that future access will benefit from automated authorization, bypassing this login screen entirely.
For more information on Google’s user experience research, you can visit http://sites.google.com/site/oauthgoog/UXFedLogin/desktopapps.
 
In addition, you may want to provide Twitter with a customized callback URL page to provide a friendly screen instructing the user that the final step in the authorization process is to return the application itself and, likely, press a button to declare they are ready to proceed.
 
Summary
 
In this chapter, (Chapter 6: Basic Authentication and OAuth of the Wrox book, Professional Twitter Development: With Examples in .NET 3.5, by Daniel Crenna), you covered how to prepare and execute OAuth web requests successfully. You are prepared to use Twitter’s preferred authentication strategy to keep your applications current and your users’ credentials safe. Specifically, you covered the following concepts and skills:
  • You learned the security risk created by using Basic authorization over HTTP.
  • You learned the benefits and spirit of the Data Portability movement.
  • You covered the OAuth specification in detail, learning how to write code for timestamps and nonce generation, handle URI escaping, use HMAC-SHA1 encryption to sign OAuth requests, and configure HttpWebRequest to send OAuth credentials.
  • You learned the OAuth workflow process, how tokens are requested and exchanged based on user authorization on the publisher site, and how an access token is used to access protected REST resources.
  • You walked through the process of using OAuth authentication with web and desktop applications, and learned about some of the challenges of structuring your user experience around OAuth for applications that aren’t hosted on the web.
In the next chapter, you will learn how to get the most of your development experience building Twitter applications on the .NET platform, including performance, asynchronous tasks, third-party services integration, and unit testing.
 
 
 

 

Tags:

Comments

4 Responses to “Twitter Development: Using OAuth to Authenticate Against the Twitter API: Walkthroughs”

  1. Anonymous says:

    where do you get all the OAuth libraries from for this,
     
    using OAuthLibrary;
    using OAuthWalkthroughConsole.Properties;
     
    Thanks,
    Hannah
    brady1063@hotmail.com

  2. Anonymous says:

    both examples have the line
    "using OAuthLibrary;"
    I did not see information about the base reference. Is it a dll? If so, where can I obtain it?

  3. Anonymous says:

    ebook of the print book please…
    In my perspective first the ebook later print copy.
     
    Greetings

Leave a Reply

What is 10 + 11 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)