I am attempting to make a Facebook application with node.js, however I'm having trouble in checking signed requests. Every time I make a request, the program throws a SyntaxError: Unexpected token ILLEGAL as such:
undefined:1
":"721599476"}
^^
SyntaxError: Unexpected token ILLEGAL
The culprit function is below:
function parse_signed_request(signed_request, secret) {
encoded_data = signed_request.split('.',2);
// decode the data
sig = encoded_data[0];
json = base64url.decode(encoded_data[1]);
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
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;
}
Just for testing, a valid signed_request would be
WGvK-mUKB_Utg0l8gSPvf6smzacp46977pTtcRx0puE.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImV4cGlyZXMiOjEyOTI4MjEyMDAsImlzc3VlZF9hdCI6MTI5MjgxNDgyMCwib2F1dGhfdG9rZW4iOiIxNTI1NDk2ODQ3NzczMDJ8Mi5ZV2NxV2k2T0k0U0h4Y2JwTWJRaDdBX18uMzYwMC4xMjkyODIxMjAwLTcyMTU5OTQ3NnxQaDRmb2t6S1IyamozQWlxVldqNXp2cTBmeFEiLCJ1c2VyIjp7ImxvY2FsZSI6ImVuX0dCIiwiY291bnRyeSI6ImF1In0sInVzZXJfaWQiOiI3MjE1OTk0NzYifQ
Why am I getting this error when it is valid JSON and simply using a static string of JSON will work fine, and are there any tips to fix this?
Thanks.
The most common way to handle JSON parse error is using try-catch block. If the JSON string is valid, it will return a JavaScript object. If the JSON string is invalid, it will throw a SyntaxError.
The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.
Exceptions. Throws a SyntaxError exception if the string to parse is not valid JSON.
A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON. parse() , and the data becomes a JavaScript object.
Ok, after a bit of testing I've fixed the problem myself, sorry for the wasted question.
Something in my base64 library wasn't decoding the string properly (although it appeared to be - so it must have been a non-displaying character or padding, etc.)
I've changed over to https://github.com/kriszyp/commonjs-utils/blob/master/lib/base64.js which suits my purposes, although needed to be modified to support base64url decoding rather than normal base64, and it seems to work fine now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With