开发者

Node.js JSON parsing error

开发者 https://www.devze.com 2023-01-31 14:59 出处:网络
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 IL

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 suc开发者_如何转开发h:

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消