HMAC Authorization
Hello again,
EDIT: Ignore the below original post, it's the get_users() functions that does not find a valid user using the public key. Any idea on why?
EDIT 2: Error resolved. Some more lines had to be added. $user = $user[0];
You can find the plugin here:
https://github.com/ViktorPontinen/HMAC-WP-API
Would love to have some input on what can be done better. Keep in mind that it is very very unpolished solution at the moment. Will update plugin and fix errors as I go.
Im building a plugin for HMAC authorization and having some trouble getting the raw POST body and the hash to match. Did some testing and it seems like there are some forward slashes that get added to the raw body. Example: What I POST:
{"content":"Testing HMAC","title":"HMAC","post":50}
What I get when I output file_get_contents('php://input');
"{\"content\":\"Testing HMAC\",\"title\":\"HMAC\",\"post\":50}"
Am I doing something wrong or does the raw body get manipulated somewhere a long the way before it reaches my plugin?
I use the following code for the authorization:
// Get raw POST body
$content = file_get_contents('php://input');
// Get X-Public and X-Hash.
$xpublic = $_SERVER['HTTP_X_PUBLIC'];
$xhash = $_SERVER['HTTP_X_HASH'];
// Set meta keys.
$private_key = 'private_example';
$public_key = 'public_example';
// Find user by Public Key
$user = get_users(array('meta_key' => $public_key , 'meta_value' => $xpublic , 'number' => '1', 'fields' => 'all' ));
// Get private key of the user.
$private_value = get_user_meta( $user->ID, $private_key, true );
// Hash the content.
$hashedcontent = hash_hmac('sha256', $content, $private_value );
// The grand finale - Check if hashes match.
if ( $xhash == $hashedcontent ) {
// Success!
return $user;
}
else {
// Fail!
$user = 0;
return $user;
}
The plugin is still in a very basic stage, but i narrowed down the error to being in the matching of the two hashes.
Am I doing something wrong or does the raw body get manipulated somewhere a long the way before it reaches my plugin?
It's possible that this is a result of magic quotes on your server. You'll likely want to do something like:
if ( get_magic_quotes_gpc() ) {
$content = stripslashes( $content );
}
Your plugin also appears to send headers and json_encode in the endpoint right now; you should return the response data instead, which will let the API handle output, and give you access to neat stuff like JSONP handling, enveloping, etc
Disclaimer: Please be exceedingly careful when writing code that touches user and login data. It's a minefield of privacy and security issues and needs to be handled with extreme care.
Hi @rmccue , Just to clarify, the error was resolved, see EDIT 2 in original post. About the plugin, the custom endpoint is just used for my own solution and has been removed for now. The main file of the plugin is hmac_auth.php, which uses the determine_current_user filter. It finds the user using public key and verifies content using private key.