Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Sample JavaScript Middleware to sign requests
var crypto = require('crypto-js');
module.exports = function requestSign(options) {
options = options || {};
return function requestSign(req, res, next) {
if (!(options.accessKey && options.secretAccessKey && options.proxy)) {
return next(new Error("options 'accessKey', 'secretAccessKey', and 'proxy' are required"));
}
var proxy = options.proxy,
protocol = options.protocol || req.protocol,
paramArray = [],
paramString = '',
signatureUrl = '',
signature = '';
req.query.key = options.accessKey;
for (param in req.query) {
paramArray.push(param + '=' + req.query[param]);
}
// Update the url with the additional key param
req.url = req.path + '?' + paramArray.join('&');
// Set the final destination as the correct host
// Otherwise, the server will use this server's host
// to calculate the signature. They must
// match.
req.headers.host = proxy
// Include post data in our signature
if (req.method === 'POST') {
for (param in req.body) {
paramArray.push(param + '=' + req.body[param]);
}
}
paramArray.sort();
signatureUrl = protocol + '://' + proxy + req.path;
paramArray.unshift(req.method, signatureUrl);
paramString = paramArray.join('&');
signature = encodeURIComponent(paramString);
signature = crypto.HmacSHA1(signature, options.secretAccessKey);
signature = crypto.enc.Base64.stringify(signature);
signature = encodeURIComponent(signature);
req.headers['Authorization'] = signature;
if (options.forceSign) req.headers['FORCE_SIGN'] = "true";
if (options.debug) {
console.log("=== Request Sign ===");
console.log("Proxy: ", proxy);
console.log("URL: ", req.url);
console.log("Query: ", req.query);
console.log("Body: ", req.body);
console.log("Signature String: ", paramString);
console.log("Signature: ", signature);
console.log("Force Sign: ", options.forceSign);
}
return next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment