Skip to content

Instantly share code, notes, and snippets.

@cmatskas
Created December 29, 2016 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cmatskas/27a89b48d63a20c6a8e5e3280cb71825 to your computer and use it in GitHub Desktop.
Save cmatskas/27a89b48d63a20c6a8e5e3280cb71825 to your computer and use it in GitHub Desktop.
DocumentDB RestAPI AuthHeader
var crypto = require("crypto");
var moment = require("moment");
let masterKey = "<your documentDB read&write key>";
let dateInRfc7231Format = moment().format("ddd, DD MMM YYYY HH:mm:ss");
let dateWithTimeZone = dateInRfc7231Format + " GMT";
console.debug(dateWithTimeZone);
// list all databases
//let result = getAuthorizationTokenUsingMasterKey("GET", "", "dbs", dateWithTimeZone, masterKey);
// list all collections within a db
//let result = getAuthorizationTokenUsingMasterKey("GET", "dbs/demodb", "colls", dateWithTimeZone, masterKey);
// create new collection
//let result = getAuthorizationTokenUsingMasterKey("POST", "dbs/demodb", "colls", dateWithTimeZone, masterKey);
// list all documents
//let result = getAuthorizationTokenUsingMasterKey("GET", "dbs/demodb/colls/student", "docs", dateWithTimeZone, masterKey);
let result = getAuthorizationTokenUsingMasterKey("POST", "dbs/demodb/colls/student", "docs", dateWithTimeZone, masterKey);
console.debug(result);
function getAuthorizationTokenUsingMasterKey(verb, resourceId, resourceType, date, masterKey) {
var key = new Buffer(masterKey, "base64");
var text = (verb || "").toLowerCase() + "\n" +
(resourceType || "").toLowerCase() + "\n" +
(resourceId || "") + "\n" +
(date || "").toLowerCase() + "\n" +
"" + "\n";
var body = new Buffer(text, "utf8");
var signature = crypto.createHmac("sha256", key).update(body).digest("base64");
var MasterToken = "master";
var TokenVersion = "1.0";
return encodeURIComponent("type=" + MasterToken + "&ver=" + TokenVersion + "&sig=" + signature);
}
@mgfink
Copy link

mgfink commented Dec 7, 2018

Can I 👍 the feedback from @ljaniszewski ? It was an easy enough fix but would be great if this worked directly for folks who's clocks aren't set to UTC by default. :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment