Posted by Sandro on August 16th, 2010

Tweetr Tutorials: Pinless OAuth in AS3

With Twitters Basic Authentication 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 AS3 Example used in this Tutorial. The zip contains a Flash Builder 4 Project Folder. 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.

The Actionscript

The Pinless OAuth process in the library uses the ExternalInterface to communicate with the Webpage
that embeds your flash application. Let’s take a look at the important bits of tweetrAS3.as:

1
2
3
4
5
6
7
8
9
10
oauth = new OAuth();
oauth.consumerKey = "YOUR_CONSUMER_KEY";
oauth.consumerSecret = "YOUR_CONSUMER_SECRET";
oauth.callbackURL = "http://tweetr.swfjunkie.com/dev/verified.html";
oauth.pinlessAuth = true;
 
oauth.addEventListener(OAuthEvent.COMPLETE, handleOAuthEvent);
oauth.addEventListener(OAuthEvent.ERROR, handleOAuthEvent);
 
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 which will be opened once authentication has succeeded on twitters side. Last but not least we define some eventlisteners and call getAuthorizationRequest to start the entire process.

The HTML/Javascript

As i said earlier, the library uses the ExternalInterface to communicate with the browser back & forth, thereby we need to add a JS File to our HTML that embeds the Flash and some little snippet of JS Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
<head>
    ... 
    <script language="JavaScript" type="text/javascript" src="js/tweetrOAuth.js"></script>
    ... 
</head>
 
<body>
 
    <div id="flashContentDiv">Your Flash might be in here..</div>
 
    <script type="text/javascript">
        OAuth.setFlashElement("myFlashID");
    </script>
 
</body>
</html>

As you see you have to include the tweetrOAuth.js file and (optimally at the end of your html) tell the OAuth Javasrcipt the ID of your flash element so that javascript can communicate with it by calling OAuth.setFlashElement.

When your Flash application calls getAuthorizationRequest from your oauth instance, it’s going to make an ExternalInterface call to the embedded javascript file which will open a popup window for you to be able to authorize the application. Once this is done, it will redirect to the callback url you have defined in your actionscript code. This Webpage should look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<head>
    ...
    <script language="JavaScript" type="text/javascript" src="js/tweetrOAuth.js"></script>
    ...
</head>
 
<body>
    ...
    <script type="text/javascript">
        OAuth.verify();
    </script>
    ...
</body>
</html>

As you see, once again we integrate our tweetrOAuth.js file. This time we call OAuth.verify since we should have received the required tokens from twitter back to our callback url. These tokens will be extracted and send back to our Flash application via ExternalInterface and the popup-window should be closed automatically.

And that’s it. When the javascript passes the token, your oauth instance will do the rest and eventually trigger an OAuthEvent.COMPLETE event in which you can pass your fully authorized OAuth instance to your tweetr instance, like so:

private function handleOAuthEvent(event:OAuthEvent):void
{
    if (event.type == OAuthEvent.COMPLETE)
    {
        tweetr.oAuth = oauth;
        // prints username, user id and the final tokens
        trace(oauth.toString());
    }
    else
    {
        trace("ERROR: "+event.text);
    }
}

Here’s a short video of the example code running:

WATCH IN 800 x 600

Related Posts
Post a Comment


61 Comments »

  1. andybrandy says:

    what doing iam wrong?

    tried to get this example running – but when i download the “doomsdayconsole” code i get many errors:
    its all about the Vector type hand how it is used, like here:
    public static function …parseForArrays(commandArgs:Vector.):Vector. {…
    Error: type parameters with a non-parameterized typ
    iam in flexbuilder 3 and flex sdk 3.3

    sorry for my bad english end the questen ;)

    comment-bottom
  2. Abdol A says:

    I downloaded your example and then uploaded the bin-debug folder to my website and then when I navigated to the example.html page and twitter pop and ask me to login and that stuff. Then it displays “redirecting…” and nothing happens after that, but when I tried the same example on tweetr.swfjunkie.com/dev/dev.html it worked and that pop up closes and displays the login data in the console. So my question is WHY THE SAME APP DIDN’T WORK ON MY WEBSITE AND WORKED IN SWFJUNKIE.COM?

    comment-bottom
  3. andy says:

    It looks like a server proxy is still required to get around the Twitter crossdomain issues when trying to use OAuth from a webpage/SWF. Is that correct?

    comment-bottom
  4. Abdol A says:

    maybe so how to fix that?

    comment-bottom
  5. andy says:

    I downloaded the PHP proxy from the codebase, but my server is IIS/PHP and the swfjunkie proxy doesn’t seem to work for me.

    comment-bottom
  6. Abdol A says:

    You can use swfjunkie’s proxy if you want but it’s some how slow.

    comment-bottom
  7. Dan says:

    Hi,

    thanks for your awesome work btw!
    I’m running into problems with my verified.html. It’s not redirecting to my application.
    Can you elaborate on how to get the “myFlashID”? I have a feeling that might cause the problem.

    Cheers!

    comment-bottom
  8. Abdol A says:

    I’ve the same problem @dan.

    comment-bottom
  9. Dan says:

    OK, I used your web auth template from the download section and got it to work.

    So I’m sure the authorization works ;) Hurray!

    Now I’d like to retrieve friends.
    I’m doing the following.

    console.print(“Authorization Successful!\n”+oauth.toString());
    var tweetr:Tweetr = new Tweetr();
    tweetr.oAuth = oauth;
    tweetr.addEventListener(TweetEvent.COMPLETE, onGetFriends);
    tweetr.addEventListener(TweetEvent.STATUS, tweetStatusHandler);
    tweetr.addEventListener(TweetEvent.FAILED, tweetFailedHandler);
    tweetr.getFriends();

    My Fail handler looks like this:
    protected function tweetFailedHandler( event:TweetEvent ):void
    {
    console.print(“Fail handler: ” + event.info );
    }

    event.info tells me there is sandbox security violation. (Error # 2048)

    It basically says, that my Server can’t load data from https://api.twitter.com/1/statuses/friends.xml?oauth…….

    I placed the crossdomain file which was created during the proxy setup in the same folder as my App.swf.

    Do I have to modify it? – I’m clueless.

    Any help would be highly apprectiated.

    Thanks,

    Dan

    comment-bottom
  10. Abdol A says:

    @dan how did you get the auth work?

    comment-bottom
  11. Abdol A says:

    Finally auth worked I don’t why but that’s great!!!

    comment-bottom
  12. pop up says:

    Thanks for your sharing!!

    comment-bottom
  13. So if i get this right, it’s no longer possible to get a protected users tweets without the really, really ugly and tacky Oauth login procedure? is the oAuth procedure only for once, or does it popup every time you need to access tweetr methods? i don’t really understand… :S

    comment-bottom
  14. Leandro says:

    the acces_token wont expire (for now)(ref. twitter dev). So if you store the user credentials with the acces_token you will only have to do the Oauth procedure once.

    comment-bottom
  15. Rafael says:

    I have the proxy instaled, the swf is on, but, when i load the swf, twitter popup opens, but it says: “This page is no longer valid. It looks like someone already used the token information you provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.”

    Can someone help?

    comment-bottom
  16. Rafael says:

    Guys, i made it!
    Just update the proxy for the 1.02b version! :)

    comment-bottom
  17. Steven says:

    I’m getting an Error #2048 when I call tweetr.getAuthorizationRequest() from my swf when it’s hosted on the web (not locally on my desktop).

    comment-bottom
  18. Dan says:

    Hi Sandro,

    I need your help with the proxy installation.
    When it comes to the testing step in the installation process I get an 404 Error. (It comes in the layout of my service provider (1und1 from Germany) )

    So at the moment I am using your proxy. (http://tweetr.swfjunkie.com/proxy)

    Everything works sweet with it but but at some point you might take it of your server or what not and then my software won’t work anymore.

    All the steps in the installation process are executed successfully. The .htaccess file is created, my server supports PHP5 and when I made a curl test call I didn’t get any errors. So curl works too.

    Can you please give me any advice on why I’m getting the 404 error and how to solve it. I really like your API. It’s straight forward and easy to understand.
    Would be great if you can help my solving this issue so I can keep using your API :)

    Thanks for sharing your fantastic work.

    Cheers,
    Dan

    comment-bottom
  19. Shukee says:

    Hi Sandro,

    Currently, I am working on a flash application(web) which will call the twitter api to post message to the users’ twitter wall.

    The whole application is coded using adobe flash professional and not flex builder. After I had run the application, it just hanged. Or should i say that it looks like it is running an infinite loop. However, after I had removed this line of code “”. Everything is looking okay. I had tested it on my localhost too with this code in it but nothing had happen. Which means that, nothing happens and there is no popups which will prompt me to authenticate user.

    Therefore, are you able to give me some advice regarding this situation?

    Your prompt response is greatly appreciated.

    Thank you,

    Cheers,

    Shukee

    comment-bottom
  20. Shukee says:

    Oh sorry, the code that is causing the problem is oauth.getAuthorizationRequest();

    My adobe flash professional will just hang like it is running an infinite loop when i had test the movie and when i tested it on a brower. Nothing had happen.

    comment-bottom
  21. Sandro says:

    @Shukee

    This call will open a popup, so you have to make sure that it is called from a user interaction (like a MouseEvent.CLICK) and that the popup is not blocked from the browser.

    @Dan

    Make sure that your server supports mod_rewrite.

    comment-bottom
  22. Shukee says:

    Hi Sandro,

    I had write a more detailed message for my problem on http://groups.google.com/group/tweetr-as3-library/topics.

    I had wrote it to the moderator. Maybe you are able to check my as3 there though.

    Sorry for the trouble. I am pretty new to flash. I will go google and see if my server supports mod_rewrite. ty.

    comment-bottom
  23. Shukee says:

    Hi Sandro,

    While configuring my application in twitter .For example if i am running my application on http://localhost/FlashTweet, , what should i type for my application url? Is there a linkage with the mod_rewrite directive?

    comment-bottom
  24. Shukee says:

    Hi Sandro,

    Sorry for the spam. I believe that i had understand why nothing is coming out. Where should i implement the html doc which is going to link up the javascript file at? Should i place the html file side by side in the same folder that I am going to publish ? And is that the only code that should be in the html file in order to link up the js for the getAuthourizationRequest method to call?

    Best Regards,
    Thank you

    comment-bottom
  25. meni says:

    Hello
    I used this code and it works but only with your API key .
    I registered for a new key but it is not working with the my key.

    What can be the problem

    comment-bottom
  26. Sandro says:

    @meni

    Make sure your Application is set to Application Type: Browser in the Application settings on twitter (http://twitter.com/apps)

    comment-bottom
  27. TJ Downes says:

    The one thing missing from the example code in the post:

    oauth.serviceHost = “http://yourdomain/proxy”;

    For web apps, you MUST use the proxy. This is not clear in the post (but hinted at in the comments) and took me some time to realize through research. There’s no way around it.

    I hope this helps someone.

    comment-bottom
  28. Paul says:

    Thanks for the excellent resource.

    Is the download page down at the moment? I can’t seem to access it.

    comment-bottom
  29. db says:

    So when i return to the site … will I always get the pop up and have to hit allow, even I have given the app permission previously?

    comment-bottom
  30. Grrrr says:

    I hate this api and OAuth and how difficult it is to use and how the DL page doesn’t work and how there are no good tutorials for Flash Pro and I hate how the proxy installed something on my server and now i can’t delete the proxy folder off my server and I can’t get this stupid thing to work. FFFFFMMMLLLL twitter. 6 hours on this so far…

    /wrist

    Why go through all the trouble of making the api and then not give people clear directions on how to use it and how it works?

    comment-bottom
  31. Grrrr says:

    I changed the App in Twitter type from “Client” to “Browser” and now it works now.

    To the Author of the tutorial videos:
    http://blog.swfjunkie.com/2009/12/tweetr-tutorials-part-2-using-oauth-in-tweetr/

    In the second video at 1:35 you say “In our case, event if it’s a web application, we need to put it as client”

    Obviously not true…

    P.S. – Thanks for the API.

    comment-bottom
  32. Abraham says:

    Hey guys just wanted to say I got it working. I was also stuck on “Redirecting…”. The solution was very simple (made me feel so stupid).
    Make sure in your index.html, the parameter in OAuth.setFlashElement(“myFlashId”); is actually the ID of your swf.

    In my case, my swf id was “TweetrTest” so you have something like:

    var attributes = { id:”TweetrTest” };

    swfobject.embedSWF(
    “TweetrTest.swf”,
    “altContent”, “100%”, “100%”, “10.0.0”,
    “expressInstall.swf”,
    flashvars, params, attributes
    );

    OAuth.setFlashElement(“TweetrTest”);

    Once I set that, I was able to publish the tweet.

    comment-bottom
  33. Hector says:

    Hello Sandro:

    First of all I would like to thankyou for this code, it seem very usefull when I try it with your proxy, the problem comes when I try to install my own proxy using your installer.

    I have Curl installed, but when I get to the part of testing the server points that there´s a “Internal Server Error”, more specific it throws this:

    “Internal Server Error

    The server encountered an internal error or misconfiguration and was unable to complete your request.

    Please contact the server administrator, hostmaster@server.tld and inform them of the time the error occurred, and anything you might have done that may have caused the error.

    More information about this error may be available in the server error log.”

    What can I do?
    Thanks in advance
    Héctor

    comment-bottom
  34. Thank you for writing this tutorial.

    it doesn’t work for me somehow!

    i’ve successfully setup the proxy, set the javascript code etc.
    The twitter popup opens up and show this error message:

    Whoa there!

    There is no request token for this page. That’s the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

    what can i do? is there part of the open-source code that i should look into?

    comment-bottom
  35. grant says:

    First off, great work. Second off, I, like a lot of people, am having issues with the proxy. I have set up the proxy, and am able to authenticate and everything just fine, however when trying to send a tweet, it get a sandbox violation (#2048) every time, telling me I cannot load data…

    Any help would be greatly appreciated!

    comment-bottom
  36. Robert Chalmers says:

    How do I extract just the username, or the user id from the oauth.toString() trace shown below from the code?

    private function handleOAuthEvent(event:OAuthEvent):void
    {
    if (event.type == OAuthEvent.COMPLETE)
    {
    tweetr.oAuth = oauth;
    // prints username, user id and the final tokens
    trace(oauth.toString());
    }
    else
    {
    trace(“ERROR: “+event.text);
    }
    }

    comment-bottom
  37. Margaret says:

    Hi,

    Thanks so much for a fantastic library. Easily implemented in a few hours to my flex web app, still working perfectly as of Jan 2013. Thanks to all the commenters too, the serviceHost requirement had me stumped for a while. i am using your proxy for the moment but will implement my own asap.

    oauth.serviceHost = “http://tweetr.swfjunkie.com/proxy”;

    Margaret

    comment-bottom
  38. kinshuk says:

    Hi,
    I am trying to use your proxy but in twitterOauth.js window.opener.OAuth.passVerifier(verifierToken) is not working for me. It says can not call passVerifier of undefined.Do you have any ideas or suggestions?

    Thanks,
    Kinshuk

    comment-bottom
  39. Je suis jeune de trente et un années , je n’ai pas de complexe là dessus !
    je suis Laurene
    Mon boulot: horticultrice … Il est dit régulièrement de moi que je parais une vraie prune.

    comment-bottom
  40. Jе m’appelle Daisi.
    Je suis agée de 41 ans .
    Je bosse comme professeur de collège ! il apparaît que je suis marrante.

    comment-bottom
  41. Howdy, i read your blog from time to time and i own a similar one and i was just curious if you get a lot of spam responses?

    If so how do you reduce it, any plugin or anything
    you can advise? I get so much lately it’s driving me insane so any support is very much appreciated.

    comment-bottom
  42. Top website Corinne

    comment-bottom
  43. Robert C says:

    Now working again at
    https://github.com/ShanghaiTimes

    The library is in source code format only. Sorry. But it does work again.

    comment-bottom
  44. Hello, i think that i saw you visited my blog so i came to return the prefer?.I’m trying to to find things to enhance my website!I guess
    its ok to make use of a few of your concepts!!

    comment-bottom
  45. Though there are many anti-inflammatory drugs out in the market that are able
    to give arthritis pain relief , proper training, exercise, food intake may slow down or prevent the development of
    arthritis. DC Universe Online Best Weapon and Power Combos .
    s martial arts classes in Sandy, children really feel that they have succeeded.

    comment-bottom
  46. I’ve read a few good stuff here. Definitely worth bookmarking for revisiting.
    I wonder how so much attempt you set to create this sort
    of magnificent informative website.

    My web page samurai siege hack

    comment-bottom
  47. Larhonda says:

    We are a group of volunteers and starting a new scheme in our community.

    Your web site provided us with valuable info to work on. You’ve done an impressive job and our
    whole community will be grateful to you.

    comment-bottom
  48. Hi to all, how is the whole thing, I think every one is getting more from this web site, and your viewws are good designed
    for new users.

    comment-bottom
  49. Polly says:

    I just could not depart your website before suggesting that I
    really loved the usual info an individual provide on your visitors?
    Is gonna be again regularly to check out new posts

    comment-bottom
  50. Heya i’m for the first time here. I came across this board and I to
    find It truly useful & it helped me out a lot. I’m hoping to offer one thing
    back and help others such as you aided me.

    comment-bottom
  51. Hi, this weekend is fastidious in support of me, because this time
    i am reading this wonderful informative piece of writing here at my residence.

    comment-bottom
  52. Flora says:

    Thanks , I have just been looking for information approximately this subject for ages
    and yours is the best I’ve came upon till now. But, what concerning
    the bottom line? Are you sure about the source?

    comment-bottom
  53. Buford says:

    You really make it seem so easy with your presentation but I find this matter to be
    really something that I think I would never understand. It seems too complicated and very broad for
    me. I am looking forward for your next post, I will try to
    get the hang of it!

    comment-bottom
  54. Leonore says:

    Hey There. I discovered your blog the usage of msn. That is a very well written article.
    I’ll be sure to bookmark it and come back to read extra of your useful information.
    Thank you for the post. I will definitely return.

    comment-bottom
  55. Hi I am so delighted I found your website, I really found you by
    accident, while I was searching on Aol for something else, Nonetheless I am here now and would just like to
    say thank you for a marvelous post and a all round enjoyable blog (I also love the theme/design),
    I don’t have time to look over it all at the moment but I have
    book-marked it and also included your RSS feeds, so when I
    have time I will be back to read a lot more, Please
    do keep up the superb job.

    Feel free to visit my web-site blue ruin télécharger

    comment-bottom
  56. Have you ever thought about including a little bit more than just your articles?
    I mean, what you say is important and all. Nevertheless imagine if you added some great images or video clips to give your posts
    more, “pop”! Your content is excellent but with images and videos, this blog could certainly be one of the most beneficial in its niche.
    Excellent blog!

    Here is my page … Qu’est-Ce Qu’on A Fait Au Bon Dieu TéLéCharger

    comment-bottom
  57. Hi there, just became aware of your blog through Google, and
    found that it is really informative. I’m going to watch out for brussels.
    I will be grateful if you continue this in future.
    A lot of people will be benefited from your writing. Cheers!

    Review my site; ets 2 wersja 1.8.2.5

    comment-bottom
  58. templates says:

    If you want to improve your knowledge only keep visiting
    this site and be updated with the hottest gossip posted
    here.

    For an awesome response please visit this post: templates

    comment-bottom
  59. this one looks a lot like my own shower I bought only recently, incredibly satisfied about
    it for anyone found on the fence when it comes to purchasing one, get it done, you will not be sorry

    Here is my website – steam shower uk

    comment-bottom
  60. looked over the information on this website a lot, going to take the leap in the near
    future and purchase a steam shower cabin, more than likely in the aftermath of
    the holiday break

    Here is my blog: steam shower tub (home-sauna-and-steam-shower.newsvine.com)

    comment-bottom
  61. After going over a few of the blog posts on your web page, I truly appreciate your technique of
    writing a blog. I bookmarked it to my bookmark webpage list and
    will be checking back in the near future. Please check
    out my web site as well and tell me what you think.

    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