It's clear that form submissions and AJAX requests, especially sensible ones, need "nonces" to avoid certain exploits. However, with heavy use of caching systems it becomes harder to generate them and output fresh nonces instead of cached ones.
To solve the problem I thought about creating an AJAX function that returns a fresh nonce, to be requested before a form is submitted. This nonce will be then appended to the form as a hidden field.
Do you think it's a safe approach?
PHP function to return a fresh nonce:
function create_nonce() {
return wp_create_nonce('my-nonce');
}
add_action('wp_ajax_create_nonce', 'create_nonce');
add_action('wp_ajax_nopriv_create_nonce', 'create_nonce');
Submit the form (request() is a custom function I've created to easily make ajax requests):
$('form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
request('create_nonce', function(nonce){
// Append the fresh nonce to the form
$form.append('<input type="hidden" name="nonce" value="'+nonce+'">');
// Proceed with the form submission...
});
});