High level AS3/Flex library for OAuth with Twitter from AIR

Recently I have played again with the Twitter API and finally have OAuth working. When I have first played with the Twitter API I have used the example from Tour de Flex. The example loads up the friends list and uses the Twitter AS3 API. The API is not really my taste but offers the functionality to build a Twitter client application. However when you want to have your client application to show up as the source of tweets you have to use OAuth for user authentication. It adds another step to get started but is a good decision to force developers to use OAuth which should provide more trust into the client app because users don’t like to enter their Twitter credentials into a 3rd party application.

After a bit of research a came across the awesome open source library oauth-as3. There were no examples yet but I remembered an Email from my friend Claus with a link to this github project. The example application uses the oauth-as3 library and demonstrates how to integrate the library.

To use OAuth in your Twitter application you need a consumerKey and consumerSecret which you can get after the registration of your client app: http://twitter.com/oauth_clients/ or go to your settings and select the “Connections” tab for an overview and further links.
However, the github example doesn’t work anymore because Twitter changed their API recently and implemented a PIN mechanism for desktop cients which should provide even more security.

So how does it work?

  1. Get the request token with your consumerKey/Secret
  2. Open the browser and pass the request token
  3. User authenticates on the Twitter site and gets a 6 digit pin code
  4. User enters pin code in the AIR app which you need to get the access token
  5. Save the accessKey/Secret in the EncryptedLocaleStorage for all further requests/sessions

I have build a high level AS3/Flex library for OAuth which is hosted on github. The library is licensed under Apache License, Version 2.0.
Check the inline comments of the IOAuth interface which should already explain the basics.

Here a little semi pseudo code example:

// create OAuth
oauth:IOAuth = new OAUth(consumerKey, consumerSecret);
 
// get request token
var loader:URLLoader = oauth.getRequestToken("http://twitter.com/oauth/request_token");
loader.addEventListener(Event.COMPLETE, requestTokenHandler);
 
function requestTokenHandler(e:Event):void
{
	requestToken = OAuthUtil.getTokenFromResponse(e.currentTarget.data as String);
	var request:URLRequest = oauth.getAuthorizeRequest("http://twitter.com/oauth/authorize", requestToken.key);
	// opens website where user has to login on Twitter and gets 6 digit pin code
	navigateToURL(request, "_blank");
}
 
function getAccessToken(pin:int):void
{
	var loader:URLLoader = oauth.getAccessToken("http://twitter.com/oauth/access_token", requestToken, {oauth_verifier:pin});
	loader.addEventListener(Event.COMPLETE, accessTokenHandler);
}
 
function accessTokenHandler(e:Event):void
{
	accessToken = OAuthUtil.getTokenFromResponse(e.currentTarget.data as String);
	// TODO store accessToken.key and accessToken.secret in EncryptedLocalStorage for all further requests
}

Instead of opening the Twitter authorization page in the browser the library also contains OAuthLoader which is a wrapper around HTMLLoader which enables to directly show the authorization page within an AIR window:

// use this in the requestTokenHandler instead of navigateToURL
var loader:OAuthLoader = new OAuthLoader();
loader.load(request);
loader.percentWidth = 100;
loader.percentHeight = 100;
var w:Window = new Window();
w.width = 800;
w.height = 400;
w.title = req.url;
w.addChild(loader);
w.open();

The OAuth library is not only considered to be used with Twitter but this was the first thing I have tested from AIR. When you build a web client there will be no pin mechanism but I haven’t tested this yet. If you have it working or see problems/bugs for web clients please drop a comment a or better file a bug.

Big thanks to Shannon Hicks for his core oauth as3 library and to Masayoshi Sekimura for the example which got me started.

Links

61 comments to High level AS3/Flex library for OAuth with Twitter from AIR

  • When you have set consumer key and secret it should work fine.
    You may wanna try my newer example for Twitter here: http://soenkerohde.com/2010/01/twitter-as3-oauth-lib-with-flex-4-example/

  • Thanks, I’ll give it a look.

  • [...] 3 simply called oauth-as3. There is not much documentation on how to use it but if found this pretty good example for using it in conjunction with AIR. The user flow is a bit different when you are integrating OAuth in a website so you have to tweak [...]

  • i know this is specifically to use oauth api to twitter .. but i’m assuming i can mod it to use it with any api? need multiple api oauth to as3 communications without problems. suggestions? thanks! :D

  • PEZ

    This is very good but it seems you can not use this library for an AS3 only project. As it is built on top of the Oauth-as3 lib which in turn relies on some Flex packages. Specifically “mx.utils.UIDUtil“. If your trying to use in an Actionscript only project there seems to be an error that can only be resolved by turning your AS3 project into a Flex Project.

  • True, you would have to replace UIDUtil with your own implementation.

  • Ken Winter

    Sönke,

    Thanks for the great library! I was able to use it successfully in an AIR app to authenticate to Twitter. But have you ever tried authenticating to any Google Data APIs using your library?

    The only changes to authenticate to Google seem to be the addition of a couple of parameters – scope, which indicates which set of apis (Calendar, Gmail, etc) you want to use, and oauth_callback – which Twitter doesn’t appear to need, but Google seems to need it set either as the URL of a web app, or the string “oob” to indicate PIN-entry authentication.

    (see http://code.google.com/apis/accounts/docs/OAuth.html and http://code.google.com/apis/accounts/docs/OAuth_ref.html for details on the Google implementation)

    It seems like it should be very straightforward to authenticate to Google, but I’ve been banging my head against a wall! According to all their docs, I’m doing everything right. And I’ve compared against requests made with their OAuth Playground (http://googlecodesamples.com/oauth_playground/index.php) – where you can go through the authentication process and see all requests, headers, strings to be signed, etc. My requests and responses as far as I can tell look just like theirs! Same string to be signed, params in the same order, it all looks good. But when I get to the final step to get an access token, I always receive a response of 400 – “The token is invalid” – no parameter errors, or signature errors, just this cryptic error.

    I don’t know if Google sees something strange in requests coming from an AIR app, or there are some undocumented differences Google requires for installed apps – I’m stumped.

    It would obviously be fantastic to build AIR apps that interact with the Google Data APIs, but I’m out of ideas. Do you have any insights or experience here? Cheers…

  • Hi, nice post

    For SWF application, how you can solve the sandbox problem?

  • Rajesh Sharma

    Hey,
    Thanks for this.
    I am using same library for Twitter and stuck with scope param which is not there in twitter API. Can you please let me know what needs to pass for Twitter.

    Thanks in advance.

  • Does anyone have an example of how to use this OAuth library in Flash Builder 4.5+?

    I’ve pasted this into my MXML file, but I’m getting hundreds of errors. Do you know why?

    import org.flaircode.oauth.*;
    import org.iotashan.oauth.*;
    import org.iotashan.utils.*;
    import flash.net.URLLoader;

    private var consumerKey:String = “myAPIKey”; // hidden for privacy purposes
    private var consumerSecret:String = ” myAPISecret”; // hidden for privacy purposes

    // create OAuth
    oauth:IOAuth = new OAuth(consumerKey, consumerSecret);

    // get request token
    var loader:URLLoader = oauth.getRequestToken(“https://myapi.req_tok.url”);
    loader.addEventListener(Event.COMPLETE, requestTokenHandler);

    function requestTokenHandler(e:Event):void
    {
    requestToken = OAuthUtil.getTokenFromResponse(e.currentTarget.data as String);
    var request:URLRequest = oauth.getAuthorizeRequest(“myapi.auth.url”, requestToken.key);
    // opens website where user has to login on Twitter and gets 6 digit pin code
    navigateToURL(request, “_blank”);
    }

    function getAccessToken(pin:int):void
    {
    var loader:URLLoader = oauth.getAccessToken(“https://myapi.access.url”, requestToken, {oauth_verifier:pin});
    loader.addEventListener(Event.COMPLETE, accessTokenHandler);
    }

    function accessTokenHandler(e:Event):void
    {
    accessToken = OAuthUtil.getTokenFromResponse(e.currentTarget.data as String);
    // TODO store accessToken.key and accessToken.secret in EncryptedLocalStorage for all further requests
    }

  • Okay, I have found your example of using this lib with Flash Builder for Twitter. However, I’m using a different API with little documentation, which doesn’t use the same call structure as Twitter, so I’m again kind of lost…