SlideShare a Scribd company logo
Building @Anywhere (for TXJS)
@Anywhere
Helping Twitter escape from
twitter.com
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
<script src="http://platform.twitter.com/
anywhere.js?3e3222e3aed"></script>

<script>
  twttr.anywhere(1, function(T) {
    T("#login").connectButton();
    T.hovercards();
    T("#comments").tweetBox();
    T("#user-details").followButton('dsa');
  });
</script>
twttr.anywhere(1, function(T) {
  T.bind('authComplete', function() {
    $('#current-user').html(
       "You are logged in as " + T.currentUser.screenName
    );

    $('#follow-me').click(function() {
      T.User.find('danwrong').follow(function() {
        alert("Thanks, man, but I probably won't follow you back");
      });
    });
  });
});
Building @anywhere
Dan Webb (@danwrong / dan@twitter.com)




                                         TM
Building Cross Domain APIs
Dan Webb (@danwrong / dan@twitter.com)




                                         TM
‣   Secure
‣   Frictionless
‣   Unobtrusive
Overview
‣   Cross domain communication
‣   Building an RPC layer
‣   Wrapping the REST API
‣   Adding Authentication and Authorization
REST API: api.twitter.com
How do we
communicate with
api.twitter.com?
Same origin policy
api.twitter.com



XMLHTTPRequest
api.twitter.com


    ✖
XMLHTTPRequest
api.twitter.com



                   XMLHTTPRequest




                  http://api.twitter.com/
                        server.html
api.twitter.com


                            ✔
                   XMLHTTPRequest




                  http://api.twitter.com/
                        server.html
api.twitter.com


                            ✔
                   XMLHTTPRequest


 Possible?
                  http://api.twitter.com/
                        server.html
<iframe>
api.twitter.com




http://api.twitter.com/
      server.html
api.twitter.com




         ✖
http://api.twitter.com/
    example.html
HTML 5: postMessage
http://api.twitter.com/
server.postMessage(‘blah’, ...);
                              example.html
// from http://twaud.io...

var $iframe = $('#twitter_server'),
    server = $iframe[0].contentWindow;

server.postMessage('Hello Twitter!',
                   'http://api.twitter.com/server.html');




// from http://api.twitter.com/server.html

window.addEventListener('message', function(event) {
  var message = event.data;
  doSomethingAmazingWith(message);
}, false);
// from http://api.twitter.com/server.html

window.parent.postMessage('Hello yourself!', '*');




// to http://twaud.io

window.addEventListener('message', function(event) {
  var reply = event.data;
  doSomethingAmazingWithReply(reply);
}, false);
Browser support for postMessage
‣   Firefox 3 and up
‣   Safari 4 and up
‣   Chrome
‣   Opera 9 and up
‣   IE 8 and up
Poor man’s postMessage
Flash LocalConnection
http://api.twitter.com/
    example.html
Building @Anywhere (for TXJS)
window.name
window.name = “{ some: ‘data’ }”




                         http://api.twitter.com/
                               server.html
var oldMessage;

function pollWindowName() {
  var message = window.name;
  if(message != oldMessage) {
    oldMessage = message;
    handle(message);
  }
}

setInterval(pollWindowName, 20);
Works in IE 6 & 7 but...
Limited message size
Problems when posting messages in quick succession
A lot less secure
Strings only (will need JSON)
Implementing RPC
var publicMethods = {
   'account/verify_credentials': function(args, uuid) {
     $.ajax('/1/account/verify_credentials.json', {
       complete: function(data) {
         sendResponseToClient({
           uuid: uuid,
           response: data
         });
       }
     });
  }
};
Sending the method call
var callbacks = [];

function remoteCall(method, args, callback) {
  var id;

    id = uuid++;
    callbacks[id] = callback;

    sendToServer({
      uuid: id,
      method: method,
      args: args
    });
}
Returning the response
function returnResponse(e) {
  var call = e.data,
      method = call.method,
      args = call.args,
      uuid = call.uuid

    publicMethods[method].call(this, args, uuid);
}
var publicMethods = {
   'account/verify_credentials': function(args, uuid) {
     $.ajax('/1/account/verify_credentials.json', {
       complete: function(data) {
         sendResponseToClient({
           uuid: uuid,
           response: data
         });
       }
     });
  }
};
Receiving the result
function receiveResult(e) {
  var result = e.data,
      uuid = result.uuid,
      response = result.response;

    callbacks[uuid].call(this, response);
}
Authentication &
Authorization
http://api.twitter.com/
remoteCall(‘method’,   [], ...);
                              example.html
Client                   User




         Authorization
Building @Anywhere (for TXJS)
@lukeshepard / sociallipstick.com
OAuth 2 (User Agent Flow)
http://wiki.oauth.net/OAuth-2.0
Client                       User

access_token=913-38h3ekjl2hc238e2238


             Authorization
How do we get the
access token to the client?
anywhere.js




SSL
http://oauth.twitter.com/2/authorize?
type=user_agent&
client_id=32ro23rfjd3&
redirect_uri=http://twaud.io/
http://oauth.twitter.com/2/authorize?
type=user_agent&
client_id=32ro23rfjd3&
redirect_uri=http://twaud.io/
http://oauth.twitter.com/2/authorize?
type=user_agent&
client_id=32ro23rfjd3&
redirect_uri=http://twaud.io/
Callback verification allows you to
prove that the site owns the client ID
anywhere.js
HTTP/1.1 302 Moved Temporarily
Date: Fri, 04 Jun 2010 19:59:41 GMT
Location: http://twaud.io/#oauth_access_token=913-...
GET / HTTP/1.1
Host: twaud.io
That’s magic!
Access token communicated back to browser securely.
No SSL support required for client site.
anywhere.js
var accessToken = parseTokenFromHash();

if (accessToken && window.opener && window.opener.setToken) {
  window.opener.setToken(accessToken);
}

self.close();
Couple of warnings	
‣   It’s secure, but not that secure
‣   Don’t store access tokens in a cookie (localStorage works)
‣   It’s fairly easy for developers to accidentally leak tokens
‣   Make them expire after a very short amount of time
‣   Can use ‘immediate’ mode to refresh expired tokens
Using the token to make
privileged calls
var callbacks = [];

function remoteCall(method, args, token, callback) {
  var id;

  id = uuid++;
  callbacks[id] = callback;

   sendToServer({
     uuid: id,
     method: method,
     args: args,
	 	 	 token: token
   });
}
var publicMethods = {
   'account/verify_credentials': function(args, uuid, token) {
     $.ajax('/1/account/verify_credentials.json', {
       beforeSend: function(xhr) {
          xhr.setRequestHeader(
	 	 	 	 	 	 'Authorization',
	 	 	 	 	 	 'Oauth oauth_access_token=' + token
	 	 	 	 	 );
       },
       complete: function(data) {
         sendResponseToClient({
             uuid: uuid,
             response: data
          });
       }
     });
   }
};
Overview
‣   Cross domain communication
‣   Building an RPC layer
‣   Wrapping the REST API
‣   Adding Authentication and Authorization
Questions?
@danwrong
@jointheflock
twitter.com/jobs

More Related Content

What's hot (20)

PDF
H4x0rs gonna hack
Xchym Hiệp
 
PDF
Guard Authentication: Powerful, Beautiful Security
Ryan Weaver
 
ODP
My app is secure... I think
Wim Godden
 
PDF
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
doughellmann
 
PDF
Protect you site with Honeypots
🏁 Pierre-Henry Soria 💡
 
KEY
Perl Web Client
Flavio Poletti
 
ODP
The promise of asynchronous php
Wim Godden
 
PDF
Learning Dtrace
JeongHun Byeon
 
PDF
Nubilus Perl
Flavio Poletti
 
PDF
QA for PHP projects
Michelangelo van Dam
 
ODP
My app is secure... I think
Wim Godden
 
PDF
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Ryan Weaver
 
PDF
Desafios do Profissionalismo Ágil
Victor Hugo Germano
 
ODP
Beyond PHP - it's not (just) about the code
Wim Godden
 
PPT
YAP / Open Mail Overview
Jonathan LeBlanc
 
ODP
My app is secure... I think
Wim Godden
 
PDF
Know your errors
Diogo Antunes
 
PDF
A Little Backbone For Your App
Luca Mearelli
 
PDF
Remote controlling Parrot AR Drone with Spring Boot & Vaadin (JavaCro15)
Peter Lehto
 
KEY
And the Greatest of These Is ... Rack Support
Ben Scofield
 
H4x0rs gonna hack
Xchym Hiệp
 
Guard Authentication: Powerful, Beautiful Security
Ryan Weaver
 
My app is secure... I think
Wim Godden
 
How I Built a Power Debugger Out of the Standard Library and Things I Found o...
doughellmann
 
Protect you site with Honeypots
🏁 Pierre-Henry Soria 💡
 
Perl Web Client
Flavio Poletti
 
The promise of asynchronous php
Wim Godden
 
Learning Dtrace
JeongHun Byeon
 
Nubilus Perl
Flavio Poletti
 
QA for PHP projects
Michelangelo van Dam
 
My app is secure... I think
Wim Godden
 
Symfony Guard Authentication: Fun with API Token, Social Login, JWT and more
Ryan Weaver
 
Desafios do Profissionalismo Ágil
Victor Hugo Germano
 
Beyond PHP - it's not (just) about the code
Wim Godden
 
YAP / Open Mail Overview
Jonathan LeBlanc
 
My app is secure... I think
Wim Godden
 
Know your errors
Diogo Antunes
 
A Little Backbone For Your App
Luca Mearelli
 
Remote controlling Parrot AR Drone with Spring Boot & Vaadin (JavaCro15)
Peter Lehto
 
And the Greatest of These Is ... Rack Support
Ben Scofield
 

Viewers also liked (6)

PDF
The Mysteries Of JavaScript-Fu (@media SF Edition)
danwrong
 
PDF
Bringing the Same-Origin Policy to its Knees
danwrong
 
KEY
Loadrunner
danwrong
 
PDF
The Mysteries Of JavaScript-Fu (RailsConf Ediition)
danwrong
 
PDF
Building Non-shit APIs with JavaScript
danwrong
 
PDF
The Mysteries Of JavaScript-Fu (@media Europe Edition)
danwrong
 
The Mysteries Of JavaScript-Fu (@media SF Edition)
danwrong
 
Bringing the Same-Origin Policy to its Knees
danwrong
 
Loadrunner
danwrong
 
The Mysteries Of JavaScript-Fu (RailsConf Ediition)
danwrong
 
Building Non-shit APIs with JavaScript
danwrong
 
The Mysteries Of JavaScript-Fu (@media Europe Edition)
danwrong
 
Ad

Similar to Building @Anywhere (for TXJS) (20)

KEY
TwitterKitではじめる OAuthスピードクッキング
Takashi Nojima
 
PDF
Mashing up JavaScript
Bastian Hofmann
 
PDF
Api
randyhoyt
 
PDF
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
PDF
Fake My Party
Tanja Otto
 
PPTX
Resiliency & Security_Ballerina Day CMB 2018
Ballerina
 
PDF
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
PDF
AuthN deep.dive—ASP.NET Authentication Internals.pdf
ondrejl1
 
KEY
@Anywhere
toddkloots
 
PPTX
Designing CakePHP plugins for consuming APIs
Neil Crookes
 
PDF
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
Matt Raible
 
PPTX
13 networking, mobile services, and authentication
WindowsPhoneRocks
 
PDF
XamarinとAWSをつないでみた話
Takehito Tanabe
 
PPTX
Security: Odoo Code Hardening
Odoo
 
PPTX
An introduction to Laravel Passport
Michael Peacock
 
ODP
Implementing Comet using PHP
King Foo
 
PDF
Is HTML5 Ready? (workshop)
Remy Sharp
 
PDF
Is html5-ready-workshop-110727181512-phpapp02
PL dream
 
PDF
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
QAware GmbH
 
PDF
YDN KR Tech Talk : Pipes 와 YQL 활용하기
Jinho Jung
 
TwitterKitではじめる OAuthスピードクッキング
Takashi Nojima
 
Mashing up JavaScript
Bastian Hofmann
 
Mashing up JavaScript – Advanced Techniques for modern Web Apps
Bastian Hofmann
 
Fake My Party
Tanja Otto
 
Resiliency & Security_Ballerina Day CMB 2018
Ballerina
 
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
AuthN deep.dive—ASP.NET Authentication Internals.pdf
ondrejl1
 
@Anywhere
toddkloots
 
Designing CakePHP plugins for consuming APIs
Neil Crookes
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
Matt Raible
 
13 networking, mobile services, and authentication
WindowsPhoneRocks
 
XamarinとAWSをつないでみた話
Takehito Tanabe
 
Security: Odoo Code Hardening
Odoo
 
An introduction to Laravel Passport
Michael Peacock
 
Implementing Comet using PHP
King Foo
 
Is HTML5 Ready? (workshop)
Remy Sharp
 
Is html5-ready-workshop-110727181512-phpapp02
PL dream
 
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
QAware GmbH
 
YDN KR Tech Talk : Pipes 와 YQL 활용하기
Jinho Jung
 
Ad

Recently uploaded (20)

PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
PDF
Market Insight : ETH Dominance Returns
CIFDAQ
 
PDF
Per Axbom: The spectacular lies of maps
Nexer Digital
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PPTX
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
PDF
introduction to computer hardware and sofeware
chauhanshraddha2007
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
PDF
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
PDF
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
TrustArc Webinar - Navigating Data Privacy in LATAM: Laws, Trends, and Compli...
TrustArc
 
Market Insight : ETH Dominance Returns
CIFDAQ
 
Per Axbom: The spectacular lies of maps
Nexer Digital
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Agile Chennai 18-19 July 2025 Ideathon | AI Powered Microfinance Literacy Gui...
AgileNetwork
 
introduction to computer hardware and sofeware
chauhanshraddha2007
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Generative AI vs Predictive AI-The Ultimate Comparison Guide
Lily Clark
 
Build with AI and GDG Cloud Bydgoszcz- ADK .pdf
jaroslawgajewski1
 
State-Dependent Conformal Perception Bounds for Neuro-Symbolic Verification
Ivan Ruchkin
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
The Future of Artificial Intelligence (AI)
Mukul
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 

Building @Anywhere (for TXJS)