Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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...
    });
});
share|improve this question
    
Are you using exceptionally long caching times or on-demand invalidation only? Nonces are good for 24 hours (as far as I remember), this is way longer than typical caching interval. –  Rarst Nov 18 '13 at 21:12
    
I considered it, but I thought it might be difficult to syncronize. This article explains it very well, however to setup cron jobs is a barrier if I wish to distribute the code as a plugin. But thanks for your comment! –  gyo Nov 19 '13 at 10:34
    
Is there any way you could publish your request() function. I'd love to see how this works in it's entirety. –  Tony Cane Eagle 2 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.