HTTP Signature is an npm package offering a node.js library with client and server components for Joyent's HTTP Signature Scheme. This package allows you to authorize and validate incoming HTTP requests based on a signature contained in the HTTP header helping you increase the security of your applications.
To use the HTTP Signature package, you start by installing it on your node.js project using the npm install command as follows: npm install http-signature
.
For client-side usage, you first require the necessary modules and read your private key. Then, you specify your request options, sign the request with your key, and send it.
var fs = require('fs');
var https = require('https');
var httpSignature = require('http-signature');
var key = fs.readFileSync('./key.pem', 'ascii');
var options = {
host: 'localhost',
port: 8443,
path: '/',
method: 'GET',
headers: {}
};
//Adds a 'Date' header in, signs it, and adds the Authorization' header in.
var req = https.request(options, function(res) {
console.log(res.statusCode);
});
httpSignature.sign(req, {
key: key,
keyId: './cert.pem',
keyPassphrase: 'secret' // optional
});
req.end();
For server-side usage, you parse the incoming request and verify its signature. If the signature is verified, then you proceed with handling the request, if not; you respond with an Unauthorized status (401).
var fs = require('fs');
var https = require('https');
var httpSignature = require('http-signature');
var options = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
};
https.createServer(options, function (req, res) {
var rc = 200;
var parsed = httpSignature.parseRequest(req);
var pub = fs.readFileSync(parsed.keyId, 'ascii');
if (!httpSignature.verifySignature(parsed, pub))
rc = 401;
res.writeHead(rc);
res.end();
}).listen(8443);
The official documentation for the HTTP Signature package isn't explicitly mentioned in the readme content, but as it's an open-source project, information regarding the usage and details about the package could be found on their GitHub repository at git://github.com/joyent/node-http-signature.git. Additionally, the code examples provided in the repository are a good resource for understanding how to utilize this package.