JavaScript OAuth 1.0a signature generator (RFC 5849) for node and the browser

Overview

OAuth 1.0a signature generator for node and the browser

Compliant with RFC 5843 + Errata ID 2550 and community spec

Build Status Bower version NPM version Dependency Status

Installation

Install with npm:

npm install oauth-signature

Install with bower:

bower install oauth-signature

Add a <script> to your index.html:

<script src="/bower_components/oauth-signature/dist/oauth-signature.js"></script>

Usage

To generate the OAuth signature call the following method:

oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret, options)
  • tokenSecret is optional
  • options is optional

the default options parameter is as follows

var options = {
	encodeSignature: true // will encode the signature following the RFC 3986 Spec by default
}

Example

The following is an example on how to generate the signature for the reference sample as defined in

var httpMethod = 'GET',
	url = 'http://photos.example.net/photos',
	parameters = {
		oauth_consumer_key : 'dpf43f3p2l4k3l03',
		oauth_token : 'nnch734d00sl2jdk',
		oauth_nonce : 'kllo9940pd9333jh',
		oauth_timestamp : '1191242096',
		oauth_signature_method : 'HMAC-SHA1',
		oauth_version : '1.0',
		file : 'vacation.jpg',
		size : 'original'
	},
	consumerSecret = 'kd94hf93k423kf44',
	tokenSecret = 'pfkkdhi9sl3r4s00',
	// generates a RFC 3986 encoded, BASE64 encoded HMAC-SHA1 hash
	encodedSignature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret),
	// generates a BASE64 encode HMAC-SHA1 hash
	signature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret,
		{ encodeSignature: false});

The encodedSignature variable will contain the RFC 3986 encoded, BASE64 encoded HMAC-SHA1 hash, ready to be used as a query parameter in a request: tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D.

The signature variable will contain the BASE64 HMAC-SHA1 hash, without encoding: tR3+Ty81lMeYAr/Fid0kMTYa/WM=.

Requesting a protected resource

Use the generated signature to populate the oauth_signature parameter to sign a protected resource as per RFC.

Example GET request using query string parameters:

http://photos.example.net/photos?file=vacation.jpg&size=original&oauth_consumer_key=dpf43f3p2l4k3l03&oauth_token=nnch734d00sl2jdk&oauth_signature_method=HMAC-SHA1&oauth_signature=tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D&oauth_timestamp=1191242096&oauth_nonce=kllo9940pd9333jh&oauth_version=1.0

Advantages

This project has an extensive test coverage for all the corner cases present in the OAuth specifications (RFC 5843 + Errata ID 2550 and OAuth.net community-based specification)

Take a look at the test file src/app/signature.tests.js

How do I run tests?

The tests can be executed in your browser or in node

Browser

Open the file src/test-runner.html in your browser

You can also run them live: src/test-runner.html

Node

Execute npm test in the console

Live example

If you want to make a working experiment you can use the live version of the OAuth signature page at this url: http://bettiolo.github.io/oauth-reference-page/

And you can hit the echo OAuth endpoints at this url: http://echo.lab.madgex.com/

  • url: http://echo.lab.madgex.com/echo.ashx
  • consumer key: key
  • consumer secret: secret
  • token: accesskey
  • token secret: accesssecret
  • nonce: IMPORTANT! generate a new one at EACH request otherwise you will get a 400 Bad Request
  • timestamp: IMPORTANT! refresh the timestamp before each call
  • fields: add a field with name foo and value bar

A url similar to this one will be generated: http://echo.lab.madgex.com/echo.ashx?foo=bar&oauth_consumer_key=key&oauth_nonce=643377115&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1410807318&oauth_token=accesskey&oauth_version=1.0&oauth_signature=zCmKoF9rVlNxAkD8wUCizFUajs4%3D

Click on the generated link on the right hand side and you will see the echo server returning foo=bar

Maintenance

Updating uri-js/js-url

npm run update

Updating chai/mocha

Update them via npm but also manually in test-runner.html

Publish a new version

npm version [major|minor|patch]
git push
git push --tags
Comments
  • Cannot get Twitter Usertimeline with oauth-signature-js + $http request

    Cannot get Twitter Usertimeline with oauth-signature-js + $http request

    Hello !

    I've been spending days to make it work, without success...

    Here is the question on Stackoverflow: http://stackoverflow.com/questions/36961045/simple-method-to-retrieve-twitter-user-timeline

    & a plunker : https://plnkr.co/edit/kF9iqCOv31ZXuuy4vlSp?p=info

    Thank you....

    Johan

    opened by joSFD 7
  • Make Rfc3986 encoding optional

    Make Rfc3986 encoding optional

    Nice work, congrats for your effort.

    Some frameworks, like angularjs, encode parameters in their own core.

    Therefore, using your library to calculate signatures can lead to a double encoding, making necessary to decode your encode to encode it again later.

    var oauth_signature = decodeURIComponent(oauthSignature.generate(...));
    

    Would you mind to add an optional boolean parameter encode (true by default) to your OAuthSignature.prototype.generate? (or any other solution)

    I can proceed with the PR if you agree

    opened by jmendiara 7
  • Explicitly cast boolean and number values in signature base string

    Explicitly cast boolean and number values in signature base string

    So I just ran into #9 myself. I think @jmendiara has it a little mixed up in his example. Because of this line, if you were to generate a signature with parameters such as the following:

    var params = {
         from: 0,
         another: false,
         to: 1
    };
    

    The signature base string would include something like: http://foo.com/bar?from=&another=&to=1 instead of http://foo.com/bar?from=0&another=false&to=1.

    Without this, the user of the library would have to be mindful in always converting parameter values to strings. I also added tests so this fixes #9.

    Any plans on upgrading uri-js for #34 #35 #38?

    opened by okcoker 4
  • Compiled dist/ file does not work in node

    Compiled dist/ file does not work in node

    The compiled version: dist/oauth-signature.js

    Does not work in node, because it uses the window object, before any checks for the window object:

    /*! url - v1.8.6 - 2013-11-22 */window.url=functi ....
    ;(function() {
        'use strict';
    
        // In node there is no global Window object
        var isNode = (typeof window === 'undefined');
    
    opened by StuAtGit 4
  • Add partial support for falsy parameters

    Add partial support for falsy parameters

    Cause falsy permissive comparisons, all falsy values are considered '' when computing the signature

    var parameters = { 
     a: '',
     b: null,
     c: undefined,
     d: false,
     e: 0,
     f: [],
     g: true,
     h: 1
    };
    //...
    var signature = oauthSignature.generate(httpMethod, url, parameters, consumerSecret, tokenSecret);
    
    //URL used for signature
    //a=&b=&c=&d=&e=&f=&g=true&h=1
    

    This PR solves the false and 0 use case, following the same approach used for true and Number, creating an URL

    //a=&b=&c=&d=false&e=0&f=&g=true&h=1
    
    opened by jmendiara 3
  • Generate invalid oauth signature

    Generate invalid oauth signature

    I imported the package in my angular project, my issue is that the function generate an invalid oauth signature. I tried to match it http://bettiolo.github.io/oauth-reference-page/ with the same data/parameters but the oauth signature does not match. Here's my code.

    var httpMethod = 'GET';
    var url = 'https://api.xero.com/oauth/RequestToken';
    this.parameters = {
        oauth_consumer_key : '<consumer key>',
        oauth_nonce : '366871832',
        oauth_timestamp : '1521616286',
        oauth_signature_method : 'HMAC-SHA1',
        oauth_version : '1.0'
    
    };
    var consumerSecret = '<consumer secret>';
    var encodedSignature = oauth.generate(httpMethod, url, this.parameters,consumerSecret);
    var signature = oauth.generate(httpMethod, url, this.parameters, consumerSecret,
      { encodeSignature: false });
    
    opened by cenezoic12 2
  • SOS,when i am exchange token, the signature is wrong

    SOS,when i am exchange token, the signature is wrong

    2017-07-15_000851

    but when i am in the fisrt step for request token, it works well, the signature is right, the param 'tokenSecret' is empty, just when i put in the param 'tokenSecret' in the next step, the signature is wrong.

    why? help me, the cryto function works bad when the the param 'tokenSecret' is set ?

    Thx

    ----I have already solved it .-----

    opened by shadowprompt 1
  • [Snyk Alert] Fix for 1 vulnerable dependency path

    [Snyk Alert] Fix for 1 vulnerable dependency path

    New vulnerabilities have been disclosed, and this project is affected. This pull request fixes one or more vulnerable packages in the npm dependencies of this project.

    The PR includes:

    • Changes to package.json to upgrade the vulnerable dependencies to a fixed version.

    Vulnerabilities that will be fixed

    With an upgrade:

    As these vulnerabilities are now publicly known, attackers can try to use them against your application, making fixing them a matter of urgency.

    You can read more about Snyk's upgrade and patch logic in Snyk's documentation.

    Note that this pull request only addresses the newly disclosed vulnerabilities mentioned above. See the Snyk test report for this project to review and fix the full list of vulnerabilities.

    Check the changes in this PR to ensure they won't cause issues with your project.

    Stay secure, The Snyk team

    opened by snyk-bot 1
  • Invalid encoded signature with

    Invalid encoded signature with "ä ü ö" in url argument

    Hi Marco

    Thanks for this awesome tool. I used it in one of my Udacity Nanodegree projects to authenticate an ajax call to yelp. However, when the yelp-id for a business - which is part of the url - contains an umlaut (ö, ü, ä), then the returned encoded oauth signature is invalid.

    Github project name: neighbourhood-map File: src/js/app.js Lines: 20-75 and 272-286

    opened by thomasgrusz 1
  • Browserify compatibility

    Browserify compatibility

    oauth-signature-js checks if a "window" global object exists to determine if it is running in the browser. While this works alone, it does not work when in conjunction with Browserify.

    Browserify emulates Node's "module" global to properly expose objects. In order to work with Browserify (or Node "emulation") I modified the isNode flag to check for the non-existence of the module and module.exports global, instead of checking for the existence of the window global.

    I don't know of a simple way to test that the code works with browserify and the current code does not. I added a test to prove that the "old" and "new" method of detection both return the same value when tested in the browser or in Node. Thus, no current implementations should be hindered by the update.

    opened by DigitalIO 1
  • ADD bower support

    ADD bower support

    To add this project to bower, you have to perform the following steps:

    Register the package in bower:

    • npm install -g bower
    • bower register oauth-signature https://github.com/bettiolo/oauth-signature-js.git

    When releasing a new version:

    • Increment bower.json version as you make in package.json
    • Create a git tag for the version (ex: git tag 1.1.4 and git push --tags or make a Github Release)

    Thats it. No need to publish to bower cause it uses your github tags for versioning

    opened by jmendiara 1
  • using hmac-sha256

    using hmac-sha256

    Hi, I am trying to use oauth_signature_method HMAC-SHA256, but it seems like its not supported (Auth fails). Can you please explain how to use this?

    Thanks,

    opened by ShiraBoa 1
  • Using vulnerable crypto-js version

    Using vulnerable crypto-js version

    https://app.snyk.io/vuln/SNYK-JS-CRYPTOJS-548472 Insecure Randomness affecting crypto-js package, versions <3.2.1

    Affected versions of this package are vulnerable to Insecure Randomness. The secureRandom() method is supposed to return a cryptographically strong pseudo-random data string, but it is biased to certain digits. An attacker could be able to guess the created digits.

    Remediation Upgrade crypto-js to version 3.2.1 or higher.

    References GitHub Commit

    GitHub Issue

    opened by mkj28 0
  • Example HTML for the given oAuth example

    Example HTML for the given oAuth example

    Hi,

    I'm very new to javascript. I'm trying to use the js for a filemaker project. Right now I'm very unable to get the example working in a regular html file.

    Have a pretty simple HTML (textfile below) but all I get is a blank page. I'd expect a signature in the browser window.

    Can someone point me in the right direction?

    Thanks, Taco

    TacoTest.txt

    opened by TacodeJong 5
  • oauthSignature is undefined in react-native

    oauthSignature is undefined in react-native

    This may seem very basic but I'm stuck over here. I am getting the error oauthSignaure is undefined. I am trying to import it like: import oauthSignature from 'oauth-signature';

    Also I have tried to use require with require() as well, but it doesn't work. Please let me know how can I use it with react-native?

    opened by imsateesh 3
Releases(v1.5.0)
RESTful HTTP client for JavaScript powered web applications

Amygdala is a RESTful HTTP library for JavaScript powered web applications. Simply configure it once with your API schema, and easily do GET, POST, PU

Lincoln Loop 392 Dec 6, 2022
Job scheduler and rate limiter, supports Clustering

bottleneck Bottleneck is a lightweight and zero-dependency Task Scheduler and Rate Limiter for Node.js and the browser. Bottleneck is an easy solution

Simon Grondin 1.4k Jan 3, 2023
Bearer provides all of the tools to build, run and manage API integrations.

Bearer - The API Integration Framework Bearer provides all of the tools to build, run and manage API Learn more Archive Status Bearer JS has been arch

Bearer.sh 22 Oct 31, 2022
Optic documents and tests your API as you build it

Optic uses real traffic to document and test your APIs Language agnostic, works with any Rest API Optic observes development traffic and learns your A

Optic 1k Dec 31, 2022
⚛️ Hooks for fetching, caching and updating asynchronous data in React

Hooks for fetching, caching and updating asynchronous data in React Enjoy this library? Try the entire TanStack! React Table, React Form, React Charts

Tanner Linsley 32k Dec 31, 2022
⚡️The Fullstack React Framework — built on Next.js

The Fullstack React Framework "Zero-API" Data Layer — Built on Next.js — Inspired by Ruby on Rails Read the Documentation “Zero-API” data layer lets y

⚡️Blitz 12.5k Jan 4, 2023
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

WebSocket Client & Server Implementation for Node Overview This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and

Brian McKelvey 3.6k Dec 30, 2022
I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certificate. I use node-signpdf and pdf-lib library.

pdf-digital-signature-with-node-signpdf-ejs I'm trying to create simple program for adding the digital signature to a pdf file with self-signed certif

null 5 Dec 25, 2022
Node JS utility to check the signature of Apple P12 Certificates.

CertCheck Node JS utility to check the signature of Apple P12 Certificates. Confirmed to work on macOS and Linux. Windows may need slight changes. Wor

Jailbreaks.app Team 10 Dec 24, 2022
Wrap native HTTP requests with RFC compliant cache support

cacheable-request Wrap native HTTP requests with RFC compliant cache support RFC 7234 compliant HTTP caching for native Node.js HTTP/HTTPS requests. C

Luke Childs 259 Dec 20, 2022
Use plain functions as modifiers. Polyfill for RFC: 757 | Default Modifier Manager

Use plain functions as modifiers. Polyfill for RFC: 757 | Default Modifier Manager

null 7 Jan 14, 2022
Calculate the Mexican RFC as specified by the SAT (Servicio de Administración Tributaria) for Personas Físicas

About The Project This project calculates a "Persona Física"'s RFC based on SAT's specifications including homonymy and verification digit. Built With

null 4 Nov 6, 2022
📋 Todo List CRUD and OAuth with Firebase

Todo List CRUD and OAuth with Firebase Esta es una app hecha con React y Firebase en la que puedas crear, leer, actualizar y borrar tareas dentro de u

Adonys Santos 4 May 28, 2022
Reward your community using NFTs and thirdweb's signature based minting.

Community Rewards Example Introduction In this guide, we will utilize signature-based minting of NFTs as a mechanism to reward users of a specific com

thirdweb examples 18 Jan 2, 2023
OAuth Proxy

Grant OAuth Proxy 200+ Supported Providers / OAuth Playground 23andme | 500px | acton | acuityscheduling | aha | alchemer | amazon | angellist | apple

simo 3.8k Jan 3, 2023
Simple implementation of online contract signature.

react-pdf-signaturer Simple implementation of online contract signature. Example online demo: https://buynao.github.io/react-pdf-signaturer/ Usage $ g

law 20 Nov 28, 2022
Remix Auth plugin for Twitter OAuth 1.0a

Remix Auth Twitter Remix Auth plugin for Twitter OAuth 1.0a. Supported runtimes Runtime Has Support Node.js ✅ Cloudflare ✅ Demo Try out live demo (sou

na2hiro 13 Dec 31, 2022