Giter Club home page Giter Club logo

jsoauth's Introduction

[Abandoned]

This library is old and unmaintained. There are far better and more modern alternatives.

jsOAuth - JavaScript OAuth library

jsOAuth is a javascript library implementing the OAuth protocol. jsOAuth aims to form the basis of custom clients such as Twitter and Yahoo.

Written in JavaScript, jsOAuth aims to be a fully featured open source OAuth library for use in Adobe AIR, Appcelerator Titanium and PhoneGAP. In fact, anywhere that javascript can be used and has cross-domain XMLHttpRequests. For security reasons jsOAuth doesn't run in the browser. Browsers are only mentioned here for running the test suite. If you need jsOAuth in the browser, write an extension.

Released under the MIT. Please see LICENSE in the project root folder for more information.

Documentation

Find the API reference and tutorials on the Documentation site. For recipes on ways to get things working with jsOAuth, try the recipes page. If you need more help or discussion, try the Google jsOAuth Group.

Usage

Download the minified library from the distribution directory and include it in your html.

<script type="text/javascript" src="library/jsOAuth-1.3.7.min.js"></script>

This gives you a global OAuth object for you to set up and make requests with. Setting it up is simple.

<script type="text/javascript">
    var oauth, options;

    options = {
        enablePrivilege: true,
        consumerKey: 'ba9df9055c77f338',
        consumerSecret: '846ffe1ec3b18989e73fe7fff833'
    };

    oauth = OAuth(options);
</script>

Note: EnablePrivilege lets you test jsOAuth in Firefox 3, Firefox >= 5 doesn't work
You can test in chrome using the following commandline on OSX /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --allow-file-access-from-files --allow-file-access --user-data-dir=~/chrome-test/ spec/runner.html
On Ubuntu try /opt/google/chrome/google-chrome --disable-web-security --allow-file-access-from-files --allow-file-access --user-data-dir=~/chrome-test/ spec/runner.html

You'll need to replace the consumer key and secret with your own. Once that is done, you can make your authenticated 2-legged request.

<script type="text/javascript">
    oauth.get('http://oauth-sandbox.sevengoslings.net/two_legged', function (data) {
        alert(data);
    });
</script>

Hopefully the syntax will look familier to you, if you've used any kind of javscript framework such as jQuery.

Node.js

On Node you'll need to install the XHR module with npm install xhr

Please let me know if jsOAuth doesn't work for you or if your application requires something jsOAuth doesn't currently support. I'm always happy to hear your suggestions. [email protected]

If you like jsOAuth and want to see new features, please donate.

Further reading and tutorials

Applications

Libraries

If you have a tutorial you think should be included here, please email me with links.

Building

To start developing, clone this repository and initialise the dependent git submodules by executing the following commands:

git submodule init
git submodule update

To build the entire library type make from the command line.

To build just the W3C compatible version, type make jsoauth from the command line. To build just CommonJS/Node.JS compatible module type make commonjs from the command line.

All files are compiled into the dist directory.

To start over once you have already built a copy, type make clean to delete all built distribution files

Issues

Please report all issues on the GitHub issue tracker for jsOauth.

Testing

To test I use Google Chrome

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --disable-web-security --allow-file-access-from-files --allow-file-access spec/runner.html

Authors

jsoauth's People

Contributors

bryant1410 avatar chaossteffen avatar coolhandmook avatar hyperlink avatar jeffatstepup avatar jjgonecrypto avatar liminal avatar lukaszkorecki avatar max-mapper avatar p3k avatar tecywiz121 avatar tnydwrds avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsoauth's Issues

callbackUrl

Only oob is available. create an option to callback url and use it on headerParams

headerParams = {
'oauth_callback': oauth.callbackUrl, // 'oob' - Make it flexible
'oauth_consumer_key': oauth.consumerKey,
'oauth_token': oauth.accessTokenKey,
'oauth_signature_method': oauth.signatureMethod,
'oauth_timestamp': getTimestamp(),
'oauth_nonce': getNonce(),
'oauth_verifier': oauth.verifier,
'oauth_version': OAUTH_VERSION_1_0
};

postJSON's Content-Type

I tried to use postJSON() to post something to Plurk ( http://www.plurk.com ) with OAuth ( http://www.plurk.com/API/ ) but get the response "function arguments invalid. (2 missing, 0 additional)" .
So I checked the http request ( see https://lh4.googleusercontent.com/-6QJVff5Rlvw/TiUEOH-0wnI/AAAAAAAADBo/9RSSy9gpKJg/s912/postJSON-2.png ) and it's because postJSON() send the wrong content-type "text/plain" , can I use postJSON() with content-type = 'application/x-www-form-urlencoded' or must use oauth.request() to do what I want to do ?

=== code as bellow ===
$( '#plurkAdd' ).click( function() {

  var plurk_content = $( '#plurk_content' ).val();
  if( plurk_content != '' ) {
    var params = new Object();
    params.content = plurk_content;
    params.qualifier = 'says';
    params.lang = 'tr_ch';

    // using postJSON() 
    oauth.postJSON( 
        config.TimelineAddPlurkUrl
      , params
      , function( json ) {
        console.log( "Plurk Successed !" );
        console.log( json );
      }
      , function( json ) {
        console.log( "Plurk Failure !" );
        console.error( json );
      } );

    /*
    oauth.request({'method': 'POST'
      , 'headers': { 'Content-Type': 'application/x-www-form-urlencoded' }
      , 'url': config.TimelineAddPlurkUrl
      , 'data': params
      , 'success': function( json ) {
          console.log( "Plurk Successed !" );
          console.log( json );
        }
      , 'failure': function( json ) {
          console.log( "Plurk Failure !" );
          console.error( json );
        } 
      });
    */        

  }          

URI.js line 10 missed a comma after statement, cause error in Titanium

The parser line missed a comma at end of the line, that will cause an error in Titanium Mobile SDK 1.7.2 on iPhone Device.

Error message is:

message = "Left side of assignment is not a reference.";

Just add a comma will fix this issue.

        var args = arguments, args_callee = args.callee,
            parsed_uri, scheme, host, port, path, query, anchor,
            parser = /^([^:\/?#]+?:\/\/)*([^\/:?#]*)?(:[^\/?#]*)*([^?#]*)(\?[^#]*)?(#(.*))*/
            uri = this;

Uncaught ReferenceError: netscape is not defined

Hi,

I'm using jsOAuth-1.3.6.min.js and whenever I try to make a post call I get the error:

Uncaught ReferenceError: netscape is not defined

I'm using chrome in Windows7, launched with:

Chrome --disable-web-security --allow-file-access-from-files --allow-file-access index.html

the code is:

<script type="text/javascript"> var oauth, options; options = { enablePrivilege: true, consumerKey: 'xxxx', consumerSecret: 'xxx' }; oauth = OAuth(options); oauth.post('http://api.twitter.com/oauth/request_token', function (data) { console.log(data); }); </script>

Making life simpler: Chrome iOS-Simulator App

It would be great if there are already packages included in the jsOAuth download to make testing jsOAuth in a development environment easy.

As I think its quite annoying to everytime fire up the terminal to start chrome with uncountable arguments. That's why I have created an App on Mac OSX with Automator inclusive a fancy icon to just startup Chrome with the desired setup, so testing jsOAuth code is easy for me.

Maybe the same thing is possible on Linux or even on Windows and could be included into the download of jsOAuth to give a developer an easy start with all of these new xCode, OAuth kind of things.

If there is any interest on this i could share my App with you.

Error auth Appelerator sdk version >=2

remove global
to

row 806

if (typeof global.Titanium !== 'undefined' && typeof global.Titanium.Network.createHTTPClient != 'undefined') {
XHR = global.Titanium.Network.createHTTPClient();

to

if (typeof Titanium !== 'undefined' && typeof Titanium.Network.createHTTPClient != 'undefined') {
XHR = Titanium.Network.createHTTPClient();

phonegap error, netscape is not defined

Hello,
I've already seen the similar issue about this error but I've tried the 1.3.6 and the 1.3.7 version, no luck, same error: 11-17 05:54:25.580: I/chromium(3450): [INFO:CONSOLE(1)] "Uncaught ReferenceError: netscape is not defined", source: file:///android_asset/www/js/jsOAuth-1.3.7.min.js (1).

I am using phonegap 3.6.3. Any hints? Thanks.

jsOAuth and LinkedIn

I am unable to get a oauth_verifier with the most current version of the jsOAuth (1.3.1) library running in a phonegap + jquerymobile app.

Both twitter and facebook integration runs fine. Is LinkedIn supported?

Sample code:

auth.get('https://api.linkedin.com/uas/oauth/requestToken',
function(data) {
requestParams = data.text;
console.log("Log: requestParams: " + data.text);
window.plugins.childBrowser.showWebPage('https://api.linkedin.com/uas/oauth/authorize?'+data.text,
{ showLocationBar : locbar });
},
function(data) {
alert('Error : No Authorization');
console.log("Log: 2 Error " + data);
}
);

I am redirected to the login screen
I grant access to the application I am redirected to the callback url with the oauth verifier and the oauth token.

Then I go for the accessToken

oauth.get('https://api.linkedin.com/uas/oauth/accessToken?'+verifier+"&"+requestParams,
function(data) {
alert("Data"+data);
request2Params = data.text;
console.log("Log: requestParams: " + data.text);
//window.plugins.childBrowser.showWebPage('https://api.linkedin.com/uas/oauth/accessToken?'+newParams,
// { showLocationBar : true });
},
function(data) {
alert('Error : No Authorization');
console.log("Log: 2 Error " + data.text);
}
);

I get:

OAuth realm="https%3A%2F%2Fapi.linkedin.com", oauth_problem="signature_invalid", oauth_problem_advice="com.linkedin.security.auth.pub.LoginDeniedInvalidAuthTokenException%20while%20obtaining%20request%20token%20for%20%3APOST%26https%253A%252F%252Fapi.linkedin.com%252Fuas%252Foauth%252FaccessToken%26oauth_callback%253Dhttp%25253A%25252F%25252Ftouch.www.linkedin.com%2526oauth_callback_confirmed%253Dtrue%2526oauth_consumer_key%253Dwvu23ru1wf5m%2526oauth_expires_in%253D599%2526oauth_nonce%253D682A40664D2E2043%2526oauth_signature_method%253DHMAC-SHA1%2526oauth_timestamp%253D1328751364%2526oauth_token%253Dcb516958-8206-46e7-a7c8-dfcdab220208%2526oauth_token_secret%253D134fd45d-fab2-47b3-a777-9e1fa9d9e338%2526oauth_verifier%253D68185%2526oauth_version%253D1.0%2526xoauth_request_auth_url%253Dhttps%2525253A%2525252F%2525252Fapi.linkedin.com%2525252Fuas%2525252Foauth%2525252Fauthorize%0AOAU%3Awvu23ru1wf5m%7Ccb516958-8206-46e7-a7c8-dfcdab220208%7C%2A01%7C%2A01%3A1328751364%3A%2FJNZPy%2F9tR0Ym4314pWdGDJbV2U%3D"

URL handling

Add better url handling so query string parameters can be separate from postdata

Build fails

make: *** No rule to make target src/start.js', needed bydist/jsOAuth.js'. Stop.

Support streaming responses

A feature request: I'm playing with Twitter's Streaming API, which
requires OAuth for connecting. Problem is jsOAuth does not support
streaming responses.

The get method currently looks at readystate == 4, which is the
completed state. A streaming response never does complete. So I need to
write my own request method, that does that magic I want. Problem is,
the request method is HUGE, and while I only need to monkey patch a
small part of the code, the size of the request method makes me have to
copy/paste large chunks of code. So it all sums up to this: I would like
request method to be split up into several smaller methods, so I can
write a method that works with streaming.

Dependencies

Abstract out dependencies.

  • Collection, not sure if this is possible, as params needs to be sorted and native objects cannot be sorted
  • XHR, mostly done in NS.XMLHttpRequest
  • URI, needs moving over to NS, and tested without dependencies

Version 0.7.5.2, using post in Titanium

Hi,
just found another. With the newest version it is impossible to make a post in Titanium. It changes ready state from 0 to 1 and then stops, error on console is: "Invalid arguments passed for: setRequestHeader(String, String)"

Regards
jume

No request token error

I cannot get the authentication work because there is only empty text coming back from the request token URL. Then when user is redirected to https://api.twitter.com/oauth/authorize?, twitter says that there is no request token. I am using the example on your wiki page for PIN-based authentication and trying it from a page on my hard drive and from a virtual domain linked to my localhost. Do I need to do anything else other than just copy your example code over?

XML responses

I'm testing with this library, which I like, but I' m running into issues whereas the service I'm trying to access sends XML responses to me. Is this library capable of handling XML responses or should this be implemented?

Typo in OAuth.urlEncode (version 1.3.1)

This method contains the following code:

....
for (i = 0; i < str_len; i++) {
if (c = string_arr[i].match(reserved_chars)) {
...

I'm pretty sure that the assigment to c should be a comparison instead, should read:

....
for (i = 0; i < str_len; i++) {
if (c == string_arr[i].match(reserved_chars)) {
...

data.text empty

Hi there, if i'm posting this in the wrong place please forgive me.

I'm working with jsOAuth, trying to retrieve some data from twitter:

      var oauth = OAuth({
          enablePrivilege: true,
          consumerKey: "",
          consumerSecret: "",
          accessTokenKey: "",
          accessTokenSecret:""
      });

     oauth.get("http://api.twitter.com/1/statuses/home_timeline.json", success, failure); 

I'm getting a 200 OK status in the request but the data.text retrieved is empty. Any idea?

Thanks!

Missing onerror callback for Titanium HTTPClient

when using jsOAuth-1.3.6.js with Titanium the "xhr" that is declared via Request();
xhr = Request(); should declare xhr.onerror function because titanium HTTPClient doesn't send readystate = 4 in case an error (like 401 error) accrued. therefore, the failure callback method never fires on HTTPClient error

xhr.onerror = function(e) {
var responseObject = {
error : e.error,
source : xhr,
status : this.status,
statusText : this.statusText
}
failure(responseObject);
};

umlaut handling

Hey Rob,
your code have problems in handling the german umlauts like ä,ö,ü and ß. Twitter responses with Incorrect signature to a status update containing ä, ö, ü or ß.

Regards
jume

Twitter 401 Unauthorized for get/post methods after access_token is saved

I call the oauth/request_token method and get the requestParams. Then I have the users authorize using oauth/authorize. I get and set the verifier oauth.setVerifier. Then I call oauth/access_token with the verifier and the requestParams... which successfully returns the access token and access token secret. I set the access token oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]); Then call a method to get a home_timeline.

Failed to load resource: the server responded with a status of 401 (Unauthorized) https://api.twitter.com/1/statuses/home_timeline.json

I tried other twitter endpoints and all of them throw the unauthorized error. Printing the access token it looks like it's set just fine.

I'm using the example from: https://gist.github.com/funkatron/979955

Which has:
function getHomeTimeline() {
oauth.get('https://api.twitter.com/1/statuses/home_timeline.json/',

            function(data) {
                alert('got the timeline: ' + JSON.stringify(data));
            },

            function(data) { alert('lame'); console.dir(data); }
        );          
    }

Any idea why I'm getting a 401 unauthorized? Using jsoauth version 1.3.7

postJSON - Content-Type: 'application/json'

Hi Rob,

I thought about other things that people ran into and thought of this recent support ticket. Again, great job on this library, it's helped people get up and running with JS and OAuth really quickly. Well written GitHub docs by the way. I was able to get my example running in < 10 minutes while watching TV :)

The users are basically sending/retrieving JSON through a REST API. Somebody was trying to use OAuth.postJSON to send up some JSON but it wasn't working for him. I think it's because StackMob expects the header 'Content-Type': 'application/json'. postJSON seems to call OAuth.post which in turn doesn't set that header.

I hence had him do this, since it looked like the postJSON was a convenience wrapper to stringify the json object.

oauth.request( {
method : 'POST',
headers: { 'Content-Type': 'application/json' },
url : ..., //your url
data: JSON.stringify(yourobject), //it looks like postJSON is simply a convenience wrapper that converts your object to a string via JSON.stringify
success: function(data) { console.debug(data); }, //again, using chrome console to view output
failure: function(data) { console.error('fail'); console.debug(data); }
});

Would you be able to punch a hole into post/postJSON to pass in headers - and/or should the headers for postJSON have "application/json" by default?

Erick

1.3.1 Invalid signature when using ;parameters

When using ;parameters in URL, the request fails with an "Invalid signature" message.

In my case, I had to call this URL: http://...com/xcal;all?param1=value1... This gives the "Invalid signature" error, but I managed to temporary fix it using encode() on the "xcal;all" part of the request.

Please implement a fix for this.

It's not possible to make GET requests with two query parameters having the same name

The QueryString class is an instance of Hash so at the data-structure level can only support one parameter with the same name. Both HTTP and OAuth place no restrictions on multiple query parameters with the same name. Some APIs require it as a feature.

Section 3.4.1.3.2 describes how multiple parameters of the same name must be handled. They should all be included in the base string and should be sorted by the byte order of their values.

Example use-case:

oauth.get(
    'http://www.myservice.com/api/method/?ids[]=1&ids[]=2',
    success,
    failure
);

Having problems getting this working with twitter

Hi,
I'm trying to use this to retrieve Twitter timeline data. I have an app configured under my twitter account. Using jsOAuth I get a success message back but data.text is empty. Can you assist? Here is a snippet of what I am doing (key and secret removed obviously). The consumerKey and consumerSecret values I grabbed from the OAuth settings area on my Twitter apps's detail page.
var oauthConfig = {
consumerKey: "",
consumerSecret: "",
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizationUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
};
var oauth = OAuth(oauthConfig);
function oauthSuccess(data) {
alert('Success '+data.text);
}
function oauthFailure(data) {
alert('Something bad happened!');
}
oauth.get('jsonUrl', oauthSuccess, oauthFailure);

Using requirejs breaks jsOAuth

Hi,

I'm writing a chrome extension and currently chrome has no support for commonjs modules. I am using requirejs to manage my dependencies, but due to the shims to support CommonJS modules, jsOAuth willl not work (xhr is "require"d and require exists but does not have a module named xhr. Adding a check for define being a function and define.amd gets us someway to fixing the issue but we also need to the new up window.XMLHttpRtequest explicitly when define does exist. I have this working and would be happy to submit a pull request with tests if you would consider accepting this. Unless of course you thought there might be a better approach? I thought I would test the water given the currently highly politicised debate surrounding AMD vs CommonJS.

Regards,

Raoul

Unexpected OAuth.urlDecode behavior

I was calling an OAuth REST API endpoint with a url that contained a GET parameter with spaces in it. The url encoder I was using encoded the spaces as plus symbols (+). When I passed the encoded url (eg. https://domain.com/docs?query=foo+bar ) to the getJSON method it decoded it in an unexpected way such that the plus symbol was left in place instead of being decoded to a space. Then, when the url was re-encoded before being request was made, the plus symbol was encoded as %2B which caused the server to think the character was a plus symbol instead of a space as was originally intended.

My solution to this was to use a different encoder that encoded spaces as %20 instead of plus symbols before passing the url to the OAuth library but I was wondering if this was intended behavior or accidental on the part of the OAuth library.

TL;DR

What happened:
OAuth.urlDecode('a+b') === 'a+b'

What I expected:
OAuth.urlDecode('a+b') === 'a b'

encodable query params are double percent encoded

In Consumer.js on line 431 the query params are pre-encoded before being encoded along with all the other base string values on line 457. This causes query parameters that have encodable values to be double-encoded and results in signature hash mismatches.

By my reading of the Oauth standard on building the signature base string, only the final parameters should be encoded and pre-encoding of query parameters shouldn't be done.

If I'm wrong about this, please let me know as this means there is probably a bug in the python OAuth library I'm using jsOAuth with (in which case I should report the bug to them instead..).

jsOAuth - Backbone.js

Hi

Up to now we use jsOAuth and all work perfectly but we need to move to Backbone.js, is it is it a way to use jsOAuth with Backbone.js?

Thanks.

1.3.6 error

There appears to be an error introduced in 1.3.6 with the changes starting on line 291 ("//pulled this out of this.request to be accessible from not-closure context"). When I try to POST data I get the error "Cannot call method 'push' of null " thrown on line 362 where the data is being pushed into query - which isn't declared in the var at the top of the function. Declaring it there eliminates that error, but still breaks POST operations (at least when trying to post a tweet to the twitter api in my particular case) because the data is apparently never added to the request body - content-length is always 0.

I haven't been able to track down a specific fix for this, but reverting to 1.3.4 where this was still part of the request method eliminated all the problems for me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.