Posted by Sandro on August 16th, 2010

Tweetr Tutorials: Pinless OAuth in AIR

With Twitters Basic Authentications deprecation starting today and the latest release of the Tweetr Library, it is time to give you a heads up on how to integrate OAuth without having to use the PIN Method.

First of all, make sure to download the AIR Example used in this Tutorial. The zip contains a Flash Builder 4 Project Folder as well as a Flex Project FXP File so you can import the code easily if wanted. If you don’t have Flash Builder 4 you can always just look at the code in the src folder within the zip. As you will notice, the example uses the awesome doomsdayconsole. The code for it is not included in the example but can be retrieved from its googlecode site. You will also need the AS3Crypto Library which also is not included in the example.

Without any further ado, here are the steps neccessary to get pinless OAuth working.

Let’s take a look at the important parts of tweetrAIR.as:

1
2
3
4
5
6
7
8
9
10
11
12
13
oauth = new OAuth();
oauth.consumerKey = "YOUR_CONSUMER_KEY";
oauth.consumerSecret = "YOUR_CONSUMER_SECRET";
oauth.callbackURL = "http://your.callback.url";
oauth.pinlessAuth = true; 
 
oauth.addEventListener(OAuthEvent.COMPLETE, handleOAuthEvent);
oauth.addEventListener(OAuthEvent.ERROR, handleOAuthEvent);
 
var rect:Rectangle = new Rectangle(50,50, 780, 500);
htmlLoader = HTMLLoader.createRootWindow(true, null, true, rect);
oauth.htmlLoader = htmlLoader;
oauth.getAuthorizationRequest();

As you see there’s not much to do configuration wise. First of all, we create a new OAuth instance and then assign our consumer key and consumer secret which we get from twitter (line 1-3).

The important parts here are the callbackURL and pinlessAuth at line 4 & 5. You need to set the pinlessAuth Boolean to true in order to enable (obviously) pinless authentication and you need to define a callback url for which your AIR app will be listening for. The callback url can be anything on the internet that does not redirect any further, for example “http://google.ch” or “http://yourdomain.com/static.html”. Twitter will append some GET parameters to this url for which your OAuth instance will be listening for.

Pinless Authentication for AIR Desktop Applications requires you to pass a HTMLLoader instance to your OAuth instance (see line 11 & 12). Once you have done that, you can call getAuthorizationRequest to start the entire process.

The OAuthEvent Handler Method will assign the oauth instance to twitter once an OAuthEvent.COMPLETE event is received, meaning that authentication was successful:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private function handleOAuthEvent(event:OAuthEvent):void
{
    if (event.type == OAuthEvent.COMPLETE)
    {
        // removes the authentication window
        htmlLoader.stage.nativeWindow.close();
 
        tweetr.oAuth = oauth;
 
        // prints username, user id and the final tokens
        trace(oauth.toString());
    }
    else
    {
        trace("ERROR: "+event.text);
    }
}

And that’s it. From here on out you can call any tweetr method you want. Here’s a short video of the example code running:

WATCH IN 800 x 600

Related Posts
Post a Comment


59 Comments »

  1. exoa says:

    Hi Sandro ;)
    Thank you for this tutorial, but you don’t explain what is “callbackURL”, what url should we insert here, what page ok script do we have to execute at this url ?

    thank’s a lot ;)

    comment-bottom
  2. rola says:

    hi sandro,

    after OAuthEvent.COMPLETE, it’s not possible
    to update the status – any ideas?
    tweetr.updateStatus(“abc…”);

    thank’s a lot :)

    comment-bottom
  3. exoa says:

    An perhaps it’s related to this “callback url” but, when i’m launching my app, a Windows connexion window is appearing…

    http://img231.imageshack.us/img231/5082/43133352.jpg

    any idea ?
    thank’s again ;)

    comment-bottom
  4. Sandro says:

    @exoa i’ve updated the post to explain what the callback url is, i hope that will solve your problem.

    @rola make sure that you pass your fully authorized oauth instance to your tweetr instance, for example like this:

    1
    
    myTweetrInstance.oAuth = myOAuthInstance;
    comment-bottom
  5. exoa says:

    ah okay, so i can let the one you have in your example “http://netsyndicate.net/”
    But I still have the Windows connexion, and nothing else :(
    http://img231.imageshack.us/img231/5082/43133352.jpg

    perhaps there’s a relation with my network proxy I use ?!

    comment-bottom
  6. Sandro says:

    Could you post to the google groups site and give me some more details, as in, the code you use, the network proxy you use, everything that comes to your mind.

    Thanks,
    Sandro

    comment-bottom
  7. exoa says:

    okay, my post on it is still not accepted^^
    The thing is that it’s not related to my firewall, because I totally disabled it. My code is as yours and I think i will have to downgrade if the problem continue =(

    comment-bottom
  8. ilsh says:

    I encountered the same problem with exoa’s.

    comment-bottom
  9. I am unable to extract your zip file please check again, it seem broken file.

    comment-bottom
  10. Hi Sandro:

    I got the same problem like this:
    http://img231.imageshack.us/img231/5082/43133352.jpg

    the browser is white blank and the window autorization is showed up. I have tested your zip sample codes, it works in Flex 4 but it seems not working in flex 3, is there any additional configuration you made in application config ?

    Many thanks for any help
    Reinhart

    comment-bottom
  11. I got the solution for it:

    1. The error is not from its library script
    2. You should edit your API application to browser type
    3. If you use desktop type, you not need to use browser popUp,
    it is enough you use origin window authorization from your OS.

    I hope it will be useful for you guys.

    Thank you,
    reinhart

    comment-bottom
  12. […] Tweetr Tutorials: Pinless OAuth in AIR […]

    comment-bottom
  13. Soopanova says:

    Hello. I’m just starting using actionscript 3 with various api – just finished working with Flickr authentication. What I was wondering is if it is still possible to get authorization by passing your Twitter username and password values from the app I’m building; that is, without having to open the Twitter html authentication window. I’m looking to build something like the app shown in the Tweetr examples page under Flex 3 Examples, “Sending a Tweet”. Is type of functionality still possible?

    comment-bottom
  14. starpause says:

    Great example! I was able to make it run fine from FDT using the AIR2 FDT4 ant template from beautifycode.com (Flex SDK 4.1).

    It might be wise to have this example replace the current AIR example for tweetr. It would make the library appear less broken at first glance, post 2010AUG16 =)

    Thanks!

    comment-bottom
  15. Bounce says:

    Hi,

    First off thanks for the sample. Great bit of code.
    I have a problem though but i don’t think it has anything to do with your code. I am submitting it here because twitter is not being very helpful. If i use your sample with my consumer key and secret it doesn’t work. I get a popup window asking for credentials to access the twitter api area and I never get to the login page. Any ideas on why this could be?

    Thanks a lot for your help.
    Bounce.

    comment-bottom
  16. Bounce says:

    Me again, sorry of course i had to post my problem before understanding Yacobus’ issue (which was the same as mine) and solution. Thank you Yacobus and sorry to all for the redundant post !

    comment-bottom
  17. […] an app in actionscript. I have followed a sample code written by the guys from swfjunkie ( [link] ) which works great. It does pinless authentication. The way the sample code works is very […]

    comment-bottom
  18. Sandro, could you please check your getReceivedDirectMessages and getSentDirectMessages, because they are not working any more.

    Thanks.

    comment-bottom
  19. Yogev says:

    How would you enable “remember me”? to avoid the user need to login every time he uses the app?

    comment-bottom
  20. Yogev says:

    If i get this right, to avoid getting the login popup for every time the user run my app, i should:
    1. go through the OAuth process
    2. save the oauth_token, oauth_token, user_id,_username in shared object or a database
    3. next time the app starts(if the user didn’t ask to switch user), set – oauthToken,oauthTokenSecret,_userId,_username in OAuth class.

    Any other idea? cause i don’t see support for this kind of flow, i would gladly (or if i don’t have any choice) add it, but i just want to know if i’m missing something?

    comment-bottom
  21. Yogev says:

    Yep, it worked.
    I just secretly hoped that after the user has allowed the app, twitter won’t ask for the login each time and simply return the OAuth request data.

    comment-bottom
  22. Bryce says:

    I’m getting the following error from the doomsday console. Any ideas?

    Error: Error #2071: The Stage class does not implement this property or method.
    at Error$/throwError()
    at flash.display::Stage/set tabEnabled()
    at no.doomsday.console.core::AbstractConsole/onAddedToStage()[D:\dev\Flash\doomsday\doomsdayconsole 1\fp10\src\no\doomsday\console\core\AbstractConsole.as:38]

    comment-bottom
  23. Bryce says:

    I was able to get past the error I posted earlier by downloading the doomsday source. But now I’m running into this error when I try and authenticate:

    /oauth/request_token?oauth_callback=http%3A%2F%2Fgoogle.ch%2F&oauth_consumer_key=qUGhOf08cd6KzvhD8HtGg&oauth_nonce=91863&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1296153122&oauth_version=1.0&oauth_signature=wm5uc1dwKk%2BF0xd91fhlyDLts%2FQ%3D
    Desktop applications only support the oauth_callback value ‘oob’

    As you can see, it is expecting the callback to be oop for desktop apps. Why did this work for Sandro when he is clearly running a desktop app?

    comment-bottom
  24. @Bryce:
    I believe you signed up API for desktop applicaiton, you should sign up API for web version, because desktop hasn’t callback. This is common problem for new developer, please read some comment above.

    @Sandro:
    Thanks bro for your open source opportunity, i have modified your OAuth Script fro Google Oauth Pinless, you can watch here screenr.com/YGY

    Keep us updated with your great work ;)

    Yacobus.

    comment-bottom
  25. Neil says:

    Do you plan to update the tutorial to use the WebStageView?

    comment-bottom
  26. It’s great that you’ve come up with your own implementation using HTMLLoader, but what about AIR on mobile devices (iOS in particular) using StageWebView…

    comment-bottom
  27. for iOS and android packagers for AIR, you can’t rely on tweetr implementation, you can however use StageWebView and skip the built in HTMLLoader completely…

    I’m making a tutorial, but because you might be waiting here is a quick run through my amalgamated method… so just set up tweeter and it’s oauth as normal, add the callback URL along with the other vars like so:

    oauth = new OAuth();
    oauth.consumerKey = “your_key”;
    oauth.consumerSecret = “your_secret”;
    oauth.callbackURL = “http://anything_you_want.com/”;
    oauth.serviceHost = serviceHost;

    // make sure the built in pinlessAuth is NOT set to true (defaults to false)
    // Then you have to swap the built in pinless add your stageWebView for iOS/android:

    private var stageWebView = new StageWebView();

    // add your listeners like so:

    stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, onLocationChange);
    stageWebView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, onLocationChange);
    stageWebView.addEventListener(Event.COMPLETE, onLocationChange);
    stageWebView.stage = stage;
    stageWebView.viewPort = new Rectangle(stage.stageWidth, 0, stage.stageWidth, stage.stageHeight);

    // in your OAuth event handler, swap the navigateToURL with the following

    stageWebView.viewPort = new Rectangle(0, 0, stage.stageWidth, 440); // shows the stageWebView (be careful to do it this way, it likes to crash iOS)
    stageWebView.loadURL(e.url);

    // and finally, the listener from above (every time the location changes)

    private function onLocationChange(event:Event):void {
    var location:String;
    if(event is LocationChangeEvent) {
    location = LocationChangeEvent(event).location;
    } else {
    location = stageWebView.location;
    }
    var search:String = “oauth_verifier=”;
    var ver:String = location;
    var startIndex:int = ver.lastIndexOf(search);
    if(startIndex != -1) {
    // we’ve got our pin so hide stageWebView again
    stageWebView.viewPort = new Rectangle(stage.stageWidth, 0, stage.stageWidth, stage.stageHeight);
    var ourPin = ver.substr(startIndex + search.length, location.length);
    oauth.requestAccessToken(ourPin);
    // remove listeners and dispatch success here
    }
    }

    comment-bottom
  28. Luca says:

    Hi,
    I have some little questions/problems, how to use it in AIR Application (extendedDesktop).

    I can post the first tweet with the popup authentication (all ok), but I have a “authorization failed” with the second, third, and so on.

    How can I do multiple twit (updateStatus) with only one authentication popup? Is it possible?
    How get a new requestAuth? call oauth.getAuthorizationRequest()?
    thank you in advance.

    great work,
    Luca

    comment-bottom
  29. Jason says:

    Hi

    I am trying to setup an example with this…
    However the class seems to be calling the ‘wrong’ page on twitter… (should be https://api.twitter… not http://twitter…)
    The username param seems to be read only.
    And the useAuthHeaders doesn’t seem valid.
    What am I missing ?

    Am using Flash Professional CS6 and exporting to AIR 3.2 for desktop

    Thnnaks…
    Errors:
    ReferenceError: Error #1074: Illegal write to read-only property username on com.swfjunkie.tweetr.Tweetr.
    at tweetr_fla::MainTimeline/frame1()[tweetr_fla.MainTimeline::frame1:52]

    ReferenceError: Error #1056: Cannot create property useAuthHeaders on com.swfjunkie.tweetr.Tweetr.
    at tweetr_fla::MainTimeline/frame1()[tweetr_fla.MainTimeline::frame1:49]
    ERROR: Error #2032: Stream Error. URL: http://twitter.com/oauth/request_token?oauth_callback=http%3A%2F%2Fmysite.com&oauth_consumer_key=__key__&oauth_nonce=__num__&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1343561387&oauth_version=1.0&oauth_signature=__sig__

    Code
    import flash.html.HTMLHost;
    import flash.html.HTMLWindowCreateOptions;
    import flash.html.HTMLLoader;

    import com.swfjunkie.tweetr.events.TweetEvent;
    import com.swfjunkie.tweetr.utils.TweetUtil;
    import com.swfjunkie.tweetr.data.objects.StatusData;
    import com.swfjunkie.tweetr.Tweetr;
    import com.swfjunkie.tweetr.Tweetr;
    import com.swfjunkie.tweetr.oauth.OAuth;
    import com.swfjunkie.tweetr.oauth.events.OAuthEvent;
    // create a tweetr instance
    var tweetr = new Tweetr();
    var oauth = new OAuth();
    oauth.consumerKey = “___key___”;
    oauth.consumerSecret = “___secret___”;
    oauth.callbackURL = “http://mysite.com”;
    oauth.pinlessAuth = true;
    oauth.addEventListener(OAuthEvent.COMPLETE, handleOAuthEvent);
    oauth.addEventListener(OAuthEvent.ERROR, handleOAuthEvent);

    var rect:Rectangle = new Rectangle(50,50,780,500);
    var htmlLoader = HTMLLoader.createRootWindow(true,null,true,rect);
    oauth.htmlLoader = htmlLoader;
    oauth.getAuthorizationRequest();

    function handleOAuthEvent(event:OAuthEvent):void
    {
    if (event.type == OAuthEvent.COMPLETE)
    {
    // removes the authentication window
    htmlLoader.stage.nativeWindow.close();

    tweetr.oAuth = oauth;

    // prints username, user id and the final tokens
    trace(oauth.toString());
    }
    else
    {
    trace(“ERROR: “+event.text);
    }
    }

    // set useAuthHeader to true so we actually use
    // the AIR authentication scheme
    tweetr.useAuthHeaders = true;

    // pass the username & password
    tweetr.username = “jason@jasonbarnard.com”;
    tweetr.password = “___password___”;

    // add some eventlisteners
    tweetr.addEventListener(TweetEvent.COMPLETE, handleTweetsLoaded);
    tweetr.addEventListener(TweetEvent.FAILED, handleTweetsFail);

    // call a api method
    tweetr.getUserTimeLine();

    function handleTweetsLoaded(event:TweetEvent):void
    {
    }

    comment-bottom
  30. Hi, just wanted to say, I liked this blog post. It
    was inspiring. Keep on posting!

    comment-bottom
  31. Hi there! Someone in my Facebook group shared this site with us so I came
    to look it over. I’m definitely loving the information. I’m book-marking and
    will be tweeting this to my followers! Fantastic blog and
    fantastic style and design.

    Also visit my page; Captain America le soldat de l’hiver Telecharger

    comment-bottom
  32. Ahaa, its pleasant conversation about this post here at this web
    site, I have read all that, so now me also commenting here.

    comment-bottom
  33. If some one wishes expert view concerning running a blog afterward i advise him/her to visit
    this webpage, Keep up the good work.

    my web blog; minecraft pocket edition telecharger

    comment-bottom
  34. Texter says:

    Enjoy the very hot Texter
    cause it is soo geil cool very cool.

    comment-bottom
  35. I believe this is among the such a lot significant information for me.
    And i am glad reading your article. But want to commentary on
    some basic issues, The site style is ideal, the articles is really
    excellent : D. Just right task, cheers

    Also visit my weblog :: instagram followers cheat

    comment-bottom
  36. Autumn says:

    Everything else is pretty significantly just eye candy.
    If you are considering mods, you can simply mount them.
    Many external websites over the internet claim to achieve the solution to achieving these kinds of Minecraft Gift Cide Generator premium is the reason free, however the
    majority these websites use black loath methods, and result in you not having your free gift
    codes from your Minecraft Gift Cide Turbine Gift Cide
    Generator.

    My site … More about the author (Autumn)

    comment-bottom
  37. Yes! Finally something about emulation psp sur pc.

    Feel free to visit my homepage; télécharger émulateur ps3

    comment-bottom
  38. Hello mates, pleasant post and nice arguments
    commented here, I am truly enjoying by these.

    comment-bottom
  39. Have you ever thought about writing an e-book or
    guewst authoring on other blogs? I have a blog centered on the same
    ideas you discuss and would really like to have you share some stories/information. I know
    my visitors would enjoy your work. If you are even remotely interested, feel free to send me an email.

    Also visit my web page OgłOszenia Drobne BiałYstok

    comment-bottom
  40. I blog quite often and I really thank you for your information. This great article has truly peaked my interest.
    I will take a note of your blog and keep checking for new details about once per week.
    I opted in for your RSS feed as well.

    comment-bottom
  41. I got this website from my buddy who informed me on the topic of this web site
    and now this time I am visiting this site and reading very informative posts at this
    place.

    comment-bottom
  42. Osvaldo says:

    I think this is one of the most significant info for me.
    And i’m glad reading your article. But wanna remark on few general things, The site style is great, the articles is really excellent : D.
    Good job, cheers

    comment-bottom
  43. Thank you, I have just been searching for info approximately this subject
    for a long time and yours is the greatest I have discovered
    so far. But, what about the bottom line? Are you certain concerning
    the source?

    comment-bottom
  44. Ҭhis paragraph іs genuinely a fastidious оne
    іt assists neѡ web visitors, whо ɑre wishing for blogging.

    mу homepage: csr racing hack (http://www.teen-chat.org/forums/member.php?u=86307)

    comment-bottom
  45. Your style is unique in comparison to other folks I’ve read stuff from.
    I appreciate you for posting when you have the opportunity,
    Guess I will just book mark this web site.

    Here is my webpage; Expendables 3 Télécharger

    comment-bottom
  46. Ahaa, its good dialogue about this piece of writing
    here at this web site, I have read all that, so at this time me also commenting at this place.

    comment-bottom
  47. Preserve your consciousness open and positive and acquire the maximum positive positive aspects it is possible to from your psychic reading.
    And therefore I have not appointed wives for you; for as for the spiritual
    ones of the heaven, in heaven is their dwelling.

    Is there any wonder then that the idle have
    no means for inspired activity.

    comment-bottom
  48. Excellent blog here! Also your website loads up very fast! What web host are you using?

    Can I get your affiliate link to your host? I wish my website loaded up as fast
    as yours lol

    comment-bottom
  49. game says:

    We are a group of volunteers and starting a new scheme in our community.
    Your site provided us with valuable info to work on.
    You’ve done a formidable job and our whole community will
    be grateful to you.

    comment-bottom
  50. a says:

    I take pleasure in, result in I found just what I was looking for.
    You’ve ended my 4 day long hunt! God Bless you
    man. Have a nice day. Bye

    comment-bottom
  51. In fact when someone doesn’t know afterward its up to other people
    that they will help, so here it takes place.

    comment-bottom
  52. After I originally left a comment I seem to have clicked on the -Notify me
    when new comments are added- checkbox andd from now on each time a
    comment is added I recieve fouur emails with tthe
    exact same comment. Perhapps there is a means you are able to remove me from that service?
    Thanks!

    Also visit myy page clash of clans hack android

    comment-bottom
  53. I’m gone to inform my little brother, that he should also go to see
    this webpage on regular basis to take updated from most up-to-date
    reports.

    comment-bottom
  54. Its like you read my mind! You seem to know so much about this, like
    you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but instead
    of that, this is fantastic blog. A great read. I’ll certainly be back.

    comment-bottom
  55. Heya are using WordPress for your site platform?

    I’m new to the blog world but I’m trying to get started and set up my own. Do you
    require any coding knowledge to make your own blog?
    Any help would be greatly appreciated!

    Here is my blog – Telecharger Fifa 14 Gratuit Pc

    comment-bottom
  56. Thank you a bunch for sharing this with all folks you really recognize what you are speaking about!
    Bookmarked. Kindly additionally consult with my website =).
    We may have a hyperlink change contract among us

    comment-bottom
  57. Yes! Finally something about ps3 emulator.

    my blog post; PS3 Emulator Télécharger

    comment-bottom

RSS feed for comments on this post | TrackBack URL

Leave a comment

Flash Flex Actionscript Tutorials Tutorial AS2 AS3 AS1 Feeds MXML Blog Zinc AIR Launcher Twitter Tweetr Yet Another Coverflow Liip Adobe Macromedia PHP MySQL PostgreSQL XML AMF MXNA Phidgets Schweiz Switzerland Suisse Svizzera Fribourg Freiburg Aargau Baden Publicis Accessibility JAcc Qt FOSDR Flash on the Beach Forum Conference Speaker Speaking Talk