Created
October 31, 2016 09:41
-
-
Save Jolg42/3b1b8e17356342ade4e89dc898510d3c to your computer and use it in GitHub Desktop.
FastSpring Remote Server Request MD5 Signature Check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'); | |
var router = express.Router(); | |
var _ = require('lodash'); | |
var crypto = require('crypto'); | |
var secret = 'MY_SECRET_PRIVATE_KEY'; | |
router.post('/', function (req, res) { | |
// Check User Agent | |
if (req.headers['user-agent'] !== 'FS') { | |
return res.status(401).send('Not Authorized'); | |
} | |
// Check if signature hash is present | |
if (!req.body.security_request_hash) { | |
return res.status(401).send('Not Authorized'); | |
} | |
// Sort keys in object | |
var objectSortedByKey = _(req.body).toPairs().sortBy(0).fromPairs().value(); | |
// Create concatenated string from values | |
var valuesAsConcatenatedString = _.map(objectSortedByKey, function(value, key) { | |
// Ignore Security Hash | |
if(key === 'security_request_hash') return; | |
return value; | |
}).join(''); | |
// Init MD5 hash (empty) | |
var hash = crypto.createHash('md5'); | |
// Digest MD5 based on string + secret (utf8 param required!) | |
var signature = hash.update(valuesAsConcatenatedString + secret, 'utf8').digest('hex'); | |
// Compare MD5 | |
if (req.body.security_request_hash !== signature) { | |
return res.status(401).send('Not Authorized - Bad Signature'); | |
} else { | |
console.log('Signature OK'); | |
} | |
}): |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment