Skip to content

Instantly share code, notes, and snippets.

@linkinmedo
Created July 21, 2018 18:28
Show Gist options
  • Save linkinmedo/be9d67c4ac3a02e104809ee5f2a35351 to your computer and use it in GitHub Desktop.
Save linkinmedo/be9d67c4ac3a02e104809ee5f2a35351 to your computer and use it in GitHub Desktop.
Decode Facebook signed_request with NodeJS 8+
function parse_signed_request(signed_request, secret) {
const encoded_data = signed_request.split(".",2);
// decode the data
const sig = encoded_data[0];
let buffer = new Buffer(encoded_data[1], "base64");
const json = buffer.toString("ascii");
const data = JSON.parse(json); // ERROR Occurs Here!
// check algorithm - not relevant to error
if (!data.algorithm || data.algorithm.toUpperCase() != "HMAC-SHA256") {
console.error("Unknown algorithm. Expected HMAC-SHA256");
return null;
}
// check sig - not relevant to error
const expected_sig = crypto.createHmac("sha256",secret).update(encoded_data[1]).digest("base64").replace(/\+/g,"-").replace(/\//g,"_").replace("=","");
if (sig !== expected_sig) {
console.error("Bad signed JSON Signature!");
return null;
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment