api-signed-request

Signed request server/client for token-based APIs

npm install api-signed-request
6 downloads in the last month

api-signed-request

Signed request server/client for token-based APIs. Server was written for TechShaker. Client was written for everyone else.

Server

Express-based middleware for an API.

Usage

Install using npm:

$ npm install signed-request

Inside you app:

var express = require('express');
var app = express();
var signedRequest = require('api-signed-request').Server;

app.use(signedRequest({
  useMethod: true,
  useRoute: true,
  encryption: 'sha1',
  key: 'x-api-key',
  sig: 'x-api-signature',
  allowGet: false,
  onError: function (req, res) { return res.end(401, 'Unauthorized'); },
  private: function (req, res, cb) {
      return doSomethingAsynchronous(req.header['x-api-key'], function (err, privateKey) {
          if (err) return cb(err);
          return cb(null, privateKey);
      })
  }
};
}));

app.get('/resource/:resource_id', myMiddleware);

Configuration

opts.useMethod (bool)

Include the HTTP request method in the payload. Defaults to true.

opts.useRoute (bool)

Include the HTTP request url in the payload. Defaults to true.

opts.encryption (string)

Encryption algorithm used for the payload. Uses the crypto module's encryption algorithms. Defaults to 'sha1'.

opts.key (string)

The header key containing the API Key. Defaults to "x-api-key".

opts.sig (string)

The header key containing the request signature. Defaults to "x-api-signature".

opts.allowGet (bool)

Allow non-signed requests to use GET methods. Defaults to false.

opts.onError (function)

Error middleware called when a request can't be authentified. Arguments sent are the originals req, res and next, allowing you to continue processing the request in another way instead of just finishing here. Defaults to standard HTTP "Unauthorized" message and status code.

opts.private (function)

Middleware function to get the private key associated to this request. This middleware is passed the originals req and res with a callback function (err, privateKey). If err is returned, it is passed to the next middleware. The privateKey argument is expected to be the privateKey used to verify this request's payload.

Client

Usage

var SignedRequest = require('api-signed-request').Client;
var foo = new SignedRequest(PRIVATE_KEY, 'sha1');
var payload = foo.update({ method: 'GET', route: '/user/tobi'}).digest();

Configuration

SignedRequest (private_key {string} [, encryption {string}])

Constructor function. Argument private_key is the key that'll be used to create your signature. Can be chained. Encryption defaults to 'sha1'.

SignedRequest.update(payload {object})

Adds data to the current SignedRequest object's payload. Can be chained.

SignedRequest.digest()

Returns the current SignedRequest object's signed payload. Can't be chained.

npm loves you