This repository has been archived by the owner on Mar 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
Examples: REST Authentication Headers
Daniel Linsley edited this page Jan 7, 2019
·
9 revisions
The RSA Signed canonical headers used by the CHEF Server API can be created using plugin methods:
-
Note: A much easier way to make Chef Server API request is to use the Chef Plugin for vRO. This is shown as an example of the scenarios the Encryption Plugin can assist with.
var method = "GET";
var host = "api.opscode.com:443"
var requestBody = "";
var contentHash = CryptoDigest.sha1(requestBody);
var clientPem = "" //your RSA Private Key PEM
var userId = "chefUser";
var orgName = "exampleOrg";
var path = "/organizations/"+orgName+"/nodes";
Used by example code.
function isoDateString() {
var d = new Date();
return d.getUTCFullYear() + '-' + padzero(d.getUTCMonth() + 1)
+ '-' + padzero(d.getUTCDate()) + 'T' + padzero(d.getUTCHours())
+ ':' + padzero(d.getUTCMinutes()) + ':' + padzero(d.getUTCSeconds())
+ 'Z';
}
function padzero(n) {
return n < 10 ? '0' + n : n;
}
function generateCanonicalHeader(httpMethod, path, body, userid, timestamp) {
var canonicalHeader = "Method:"+httpMethod+"\n";
canonicalHeader += "Hashed Path:"+CryptoDigest.sha1(path)+"\n";
canonicalHeader += "X-Ops-Content-Hash:"+CryptDigest.sha1(body)+"\n";
canonicalHeader += "X-Ops-Timestamp:"+timestamp+"\n";
canonicalHeader += "X-Ops-UserId:"+userid;
return canonicalHeader;
}
function splitOn60Chars(input) {
var singleLine = input.replace(/(\r\n|\n|\r)/gm,"");
var output = [];
while (singleLine.length > 0) {
var nextEntry = singleLine.substring(0,Math.min(60,singleLine.length));
output.push(nextEntry);
singleLine = singleLine.substring(Math.min(60,singleLine.length));
}
return output;
}
var headers = {};
var timestamp = isoDateString();
headers["X-Ops-Timestamp"] = timestamp;
headers["X-Ops-Userid"] = userId;
headers["X-Ops-Content-Hash"] = CryptoDigest.sha1(body);
headers["X-Ops-Sign"] = "version=1.0";
var canonical = generateCanonicalHeader(method, path, body, userId, timestamp);
var signedCanonical = CryptoRSA.createSignature(clientPem, CryptoEncoding.encodeBase64(canonical));
var splitSignedCanonical = splitOn60Chars(signedCanonical);
for (var i=0;i<splitSignedCanonical.length; i++){
headers["X-Ops-Authorization-"+(i+1)] = splitSignedCanonical[i]);
}
The signature for Authentication Header can be built using plugin methods:
var secretAccessKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
var stringToSign = "GET\n"+
"\n"+
"\n"+
"Tue, 27 Mar 2007 19:36:42 +0000\n"+
"/johnsmith/photos/puppy.jpg";
var secretAccessKeyB64 = CryptoEncoding.base64Encode(secretAccessKey);
var stringToSignB64 = CryptoEncoding.base64Encode(stringToSign);
//CryptoDigest.hmacSha1 requires both inputs to be Base64 encoded
var authSignatureB64 = CryptoDigest.hmacSha1(secretAccessKeyB64,stringToSignB64);