My site sends different data to an external API under different circumstances. Luckily, most of it happens on form submissions, but there are a few instances where I need to make an API call from the client-side when a custom event fires.
$(document).on('someCustomEvent', function() {
$.ajax({
url: '/wp-admin/admin-ajax.php',
method: 'post',
data: {
uid: $('#user-wrap').data('uid'),
action: 'add_user_by_uid',
security: addUserVars.nonce // addUserVars{} comes from wp_localize_script()
}
});
});
Then in functions.php I have:
function add_user_by_uid() {
check_ajax_referer('add_user_nonce', 'security');
$basic_auth = 'Basic ' . base64_encode( PUBLIC_KEY . ':' . PRIVATE_KEY );
$headers = array(
'Authorization' => $basic_auth,
'Content-type' => 'application/json'
);
return = wp_remote_post( '/', array(
'headers' => $headers,
'body' => json_encode(array('uid' => sanitize_text_field($_POST['uid']))
)
);
die();
}
How can I prevent someone from creating their own POST request and executing this API call from their own site (obviously at times other than when someCustomEvent
fires)?
I've always felt like using a nonce protected against this, but I've never really given it that much thought since most of my experience using AJAX in WP has not been with updating users and other critical info with a 3rd party API like this is.... Anyway, it sounds like this measure isn't terribly hard to get around. Is there a mitigation that is more appropriate for a scenario like this?