Git Product home page Git Product logo

mashape-oauth's Introduction

Mashape OAuth

OAuth Modules for Node.js - Supporting RSA, HMAC, PLAINTEXT, 2-Legged, 3-Legged, 1.0a, Echo, XAuth, and 2.0

OAuth Bible

If you're looking for the popular OAuth Bible, here it is. It extensively explains the multitude of OAuth flows and how OAuth works.

Installation

npm install mashape-oauth

Features

  • Handles binary responses
  • Handles gzipped responses
  • Supports having an empty oauth_token for 1.0a
  • Supports Plaintext, HMAC-SHA1, and RSA encryption for 1.0a
  • Object based parameter system and supports chaining
  • Code has been refactored to be more performant in loops, whiles, and callback structures.
  • Intuitive method naming, small footprint, and tested against test suites as well as hundreds of APIs.

Usage

Require the library and the one you wish to use.

  1. OAuth
  2. getOAuthRequestToken
  3. getOAuthAccessToken
  4. getXAuthAccessToken
  5. Request Methods
  6. OAuth2

Using OAuth (1.x, XAuth, Echo):

var OAuth = require('mashape-oauth').OAuth;
var oa = new OAuth({ /* … options … */ }, callback);
  • options Object OAuth request options
    • echo Object Optional If it exists we treat the request as OAuth Echo request. See Twitter
      • verifyCredentials String What is the credentials URI to delegate against?
    • realm String Optional Access Authentication Framework Realm Value, Commonly used in Echo Requests, allowed in all however: Section 3.5.1
    • requestUrl String Request Token URL. Section 6.1
    • accessUrl String Access Token URL. Section 6.2
    • callback String URL the Service Provider will use to redirect User back to Consumer after obtaining User Authorization has been completed. Section 6.2.1
    • consumerKey String The Consumer Key
    • consumerSecret String The Consumer Secret
    • version String Optional By spec this is 1.0 by default. Section 6.3.1
    • signatureMethod String Type of signature to generate, must be one of:
      • PLAINTEXT
      • RSA-SHA1
      • HMAC-SHA1
    • nonceLength Number Optional Length of nonce string. Default 32
    • headers Object Optional Headers to be sent along with request, by default these are already set.
    • clientOptions Object Optional Contains requestTokenHttpMethod and accessTokenHttpMethod value.
    • parameterSeperator String Optional Seperator for OAuth header parameters. Default is ,

getOAuthRequestToken() - Creating Request Token Call

oa.getOAuthRequestToken({ /* … parameters … */ }, callback);
  • parameters Object Optional Additional Headers you might want to pass along.
    • If omitted, you can treat parameters argument as callback and pass along a function as a single parameter.
  • callback Function Anonymous Function to be invoked upon response or failure.
Example
oa.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) {
  if (error)
    return res.send('Error getting OAuth Request Token: ' + error, 500);
  else
    // Usually a redirect happens here to the /oauth/authorize stage
    return res.send('Successfully Obtained Token & Secret: ' + oauth_token + ' & ' + oauth_token_secret, 200);
});

getOAuthAccessToken() - Creating OAuth Access Token Call

oa.getOAuthAccessToken(options, callback);
  • options Object
    • oauth_verifier String Verification code tied to the Request Token. Section 2.3
    • oauth_token String Request Token
    • oauth_token_secret String Request Token Secret, used to help generation of signatures.
    • parameters Object Optional Additional headers to be sent along with request.
    • callback Function Optional Method to be invoked upon result, over-ridden by argument if set.
  • callback Function Anonymous Function to be invoked upon response or failure, setting this overrides previously set callback inside options object.
Example
oa.getOAuthAccessToken({
  oauth_verifier: 'ssid39b',
  oauth_token: 'request_key',
  oauth_token_secret: 'request_secret'
}, function (error, token, secret, result) {
  if (error)
    return res.send('Error getting Auth Access Token: ' + error, 500);
  else
    // Usually you want to store the token and secret in a session and make your requests after this
    return res.send('Successfully Obtained Token & Secret: ' + token + ' & ' + secret, 200);
});

getXAuthAccessToken() - Creating XAuth Access Token Call

oa.getXAuthAccessToken(username, password, callback);
  • username String XAuth Username credentials of User obtaining a token on behalf of
  • password String XAuth Password credentials of User obtaining a token on behalf of
  • callback Function Anonymous Function to be invoked upon response or failure.
Example
oa.getXAuthAccessToken('nijikokun', 'abc123', function (error, oauth_token, oauth_token_secret, results) {
  if (error)
    return res.send('Error getting XAuth Access Token: ' + error, 500);
  else
    // Usually you want to store the token and secret in a session and make your requests after this
    return res.send('Successfully Obtained Token & Secret: ' + oauth_token + ' & ' + oauth_token_secret, 200);
});

Request Methods

oa.post(options, callback);
oa.get(options, callback);
oa.delete(options, callback);
oa.patch(options, callback);
oa.put(options, callback);

// Alternatively, you can use the old node-oauth style: (Where method is one of five above.)
oa.method(url, oauth_token, oauth_token_secret, body, type, parameters, callback);
  • options Object Contains Request Information
    • url String URL to be requested upon
    • oauth_token String Optional; Dependant upon request step, could be access, or request token.
    • oauth_token_secret String Optional; Dependant upon request step
    • body String Optional; Body information to be sent along with request.
    • type String Optional; Content Request Type
    • parameters Object Optional; Additional headers you wish to pass along with your request.
    • callback Function Optional; Method to be invoked upon result, over-ridden by argument if set.
  • callback Function Method to be invoked upon result, over-rides options callback.

Using OAuth2:

var OAuth2 = require('mashape-oauth').OAuth2;
var oa = new OAuth2({ /* … options … */ }, callback);
  • options Object OAuth Request Options
    • clientId String Client Identifier
    • clientSecret String Client Secret
    • baseUrl String Base url of OAuth request
    • authorizationUrl String Optional; Authorization endpoint, default is /oauth/authorize
    • authorizationMethod String Optional; Authorization Header Method, default is Bearer
    • accessTokenUrl String Optional; Access Token Endpoint, default is /oauth/access_token
    • accessTokenName String Optional; Access Token Parameter Name, default is access_token
    • headers Object Optional; Custom headers we wish to pass along

mashape-oauth's People

Contributors

adamk33n3r avatar armsteadj1 avatar bmerrifield avatar cmosnick avatar conradoplg avatar danielchatfield avatar lifecube avatar maxcountryman avatar neilco avatar nijikokun avatar opyate avatar psyklopz avatar simov avatar sonicaghi avatar subnetmarco 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  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

mashape-oauth's Issues

add JWT OAuth2 flow?

:)

thank you for the writeups to date. I find them quite useful for getting a larger eng. team up-to-date on the OAuth flows

Oauth not working request with headers.Accept='application/pdf'

I am trying to GET some content in 'application/pdf' format (PDF 1.4). I specify in the headers headers.Accept='application/pdf' and I get content that display an empty file in any PDF viewer but the file is not empty. Have a look at this code in lib/oauth.js:

if ($this.clientOptions.detectResponseContentType && utils.isBinaryContent(response)) {
data = new Buffer(0);
type = 1;
output = response;
} else if (response.headers['content-encoding'] === 'gzip') {
var gunzip = zlib.createGunzip();
data = new Buffer(0);
type = 2;
response.pipe(gunzip);
output = gunzip;
} else {
response.setEncoding('utf8');
data = "";
output = response;
}

$this.clientOptions.detectResponseContentType is undefined and it is not documented what it does or how to set it up anyway.
In regards to isBinaryContent function it returns false for PDF.
So it is the else what it is run, so we run this line:
response.setEncoding('utf8')

I have fixed it locally by adding this:
if ($this.clientOptions.detectResponseContentType && utils.isBinaryContent(response)) {
data = new Buffer(0);
type = 1;
output = response;
} else if (response.headers['content-encoding'] === 'gzip') {
var gunzip = zlib.createGunzip();
data = new Buffer(0);
type = 2;
response.pipe(gunzip);
output = gunzip;
} else if (headers.Accept=='application/pdf') {
data = new Buffer(0);
type = 1;
output = response;
} else {
response.setEncoding('utf8');
data = "";
output = response;
}

This is more a hack than a solution but I am not sure is PDF is binary file format and I am not sure how do you use $this.clientOptions.detectResponseContentType.

Markdown Verbatim Formatting Broken in 2 Places

Too lazy to fork just to make a PR, and I can't make a branch, so just dumping the diff here:
image
(pasting that in text would be a pain to format, but if anyone's maintaining this, have at it. there seem to be PRs up for 1 of these errors)

OauthAccessToken > 400 signature invalid from Google

Hello again,
I'm still struggling with oauth and google :(
I thought you could help me again.

    oauthCallback: (req, res) ->
        options =
            oauth_verifier: req.query.oauth_verifier
            oauth_token: req.query.oauth_token
            oauth_secret: oauthTemp.secret

        oa.getOAuthAccessToken options, (err, token, secret, result) ->
            if err?
                console.log "Error while retrieving access token: "
                console.log "#{err.statusCode}-#{err.data}"
            else
                console.log token
                console.log secret
                console.log result

oauthTemp.secret is saved in memory during the token request so the values are correctly set (checked with a console.log)
Google sends me an error though:

400-signature_invalid
base_string:POST&https%3A%2F%2Fwww.google.com%2Faccounts%2FOAuthGetAccessToken&oauth_consumer_key%3Danonymous%26oauth_nonce%3DXGu9LzCsKfi7OQGJaZdUY6Hg31ke6FDy%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1375171680%26oauth_token%3D4%252Fykmunc9yFfiUSzXVt88yRlbbl2Om%26oauth_verifier%3D3kCK4GcX96CBvnNlmar56A6T%26oauth_version%3D1.0

Full code is available at https://github.com/jsilvestre/cozy-data-integrator/blob/master/server/controllers/integrator.coffee

If you can see what is wrong I'd be very grateful!
Thank you in advance.

authHeader() throws "TypeError: context.hasOwnProperty is not a function" when body is a query string

authHeader() -> prepareParameters() -> utils.extend()

prepareParameters() parses the body using "querystring"."parse()". utils.extend then attempts to call ".hasOwnProperty()" on the parsed querystring object. This property doesn't exist, due to missing prototype inheritance. The node.js documentation states:

Note: The object returned by the querystring.parse() method does not prototypically inherit from the JavaScript Object. This means that typical Object methods such as obj.toString(), obj.hasOwnProperty(), and others are not defined and will not work.

Tested on Node v6.9.1.

Incorrect callback URL with oAuth 1.0a / Google

Hi there,

I'm trying to use oAuth 1.0a with Google to retrieve stuff (I can't use 2.0 for this use case).
I'm struggling at the authorization step because Google doesn't redirect my URL correctly and I was wondering what I am doing wrong. I thought you might help me or notice if it is a bug on mashape-oauth side.

Here is my code: https://github.com/jsilvestre/cozy-data-integrator/blob/master/server/controllers/integrator.coffee#L28-L49

Here is the result + chrome debugger information: http://d.pr/i/eQtK
The weird part is that Google redirects to /b/0/ instead of the callback itself.
Using http://googlecodesamples.com/oauth_playground/index.php gives me a correct result though.

Notice that I still have the same result even if I use a different callback URL.

Thank you in advance if you can help me!

Dropbox - Unknown field `type`

Hi,
I'm not very familiar with the OAuth2 spec, but I'm wondering why this parameter is hardcoded?

args.type = 'web_server';

Dropbox have somewhat more strict rules about the parameters and complaints about not knowing about the type field, so unless I comment out these two lines, the OAuth2 flow can't proceed.

promise support?

any interest in adding support for Promise? trying to avoid callbacks for an SDK that i'm building so I can take advantage of async/await.

npm version is out of date

When I install the package from npm. Some functions (like getXAuthAccessToken) have unhandled error. Please republish the lasted version to npm.

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.