Skip to content

Instantly share code, notes, and snippets.

@GiancarloGomez
Last active September 7, 2016 05:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GiancarloGomez/9114595f6976ca2b6d7c1d8c65e76aee to your computer and use it in GitHub Desktop.
Save GiancarloGomez/9114595f6976ca2b6d7c1d8c65e76aee to your computer and use it in GitHub Desktop.
Code to handle the Facebook Login Deauthorize Callback URL (http://www.giancarlogomez.com/2016/09/how-to-set-up-facebook-login.html)
<cfscript>
// Usage
appSecret = "You App Secret Here";
theUser = parseSignedRequest(form.signed_request,appSecret);
// if succesful you will see the entire struct
writeDump(theUser);
// the user id will be available as follows
writeOutput(theUser.user_id);
/**
* Parses a facebook deauth request
* Based on code from the following URLs
* https://www.exchangecore.com/blog/facebook-deauthorization-callback-yii/
* http://stackoverflow.com/questions/11973251/how-to-read-facebook-signed-request-to-get-user-id
*/
function parseSignedRequest(string signedRequest,string appSecret){
var theRequest = listToArray(arguments.signedRequest,".");
// decode the data
var signature = base64Decode(theRequest[1]);
var data = deserializeJSON(base64Decode(theRequest[2]));
// confirm the signature
var expectedSignature = hmacEncrypt(theRequest[2],arguments.appSecret);
// throw error if not valid
if (compare(expectedSignature,signature))
throw(message:"Bad Signed JSON signature!");
// returns struct
return data;
}
/**
* Decodes a base64 string from the deauth request
* First replaces all occurances of _ with / and then add = at end of string
* for toBinary and/or binaryDecode to work
*/
function base64Decode(string input) {
return toString(toBinary(arguments.input.replaceAll("_","/") & "="));
}
/**
* function supplied by David Mulder on the following post
* http://stackoverflow.com/questions/10331980/coldfusion-equivalent-to-php-hash-hmac
*
* I updated to return string instead of binary to mimic PHP example
*/
function hmacEncrypt(string signMessage, string signKey){
var jMsg = JavaCast("string",arguments.signMessage).getBytes("iso-8859-1");
var jKey = JavaCast("string",arguments.signKey).getBytes("iso-8859-1");
var key = createObject("java","javax.crypto.spec.SecretKeySpec");
var mac = createObject("java","javax.crypto.Mac");
key = key.init(jKey,"hmacSHA256");
mac = mac.getInstance(key.getAlgorithm());
mac.init(key);
mac.update(jMsg);
return toString(mac.doFinal());
}
</cfscript>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment