0

I'm trying to build a central system that will delegate certain functionality and serve me some nice things when dealing with AJAX calls. Basically, I want to dumb the whole charade of checking parameters, making sure they're alright, making sure the user has the right capabilities, etc. into one single system.

There is a problem with nonces however. To my understanding and just reading through it, a nonce is supposed to simply protect against CSRF. It's a simple mechanism of generating an unique string based on who the user is, the action & the time.

Problem is that, the nonce has to always be localized to the script that's going to pass it as the security argument when making an AJAX call. This means that the back-end cannot know how the nonce is called beforehand.

If I do:

<?php
//Set Your Nonce
$ajax_nonce = wp_create_nonce( "wpdocs-special-string" );
?>

<script type="text/javascript">
jQuery(document).ready(function($){
    var data = {
        action: 'wpdocs_action',
        security: '<?php echo $ajax_nonce; ?>',
        wpdocs_string: 'Hello World!'
    };
    $.post(ajaxurl, data, function(response) {
        alert("Response: " + response);
    });
});
</script>

which is equivalent to wp_localize_script with the nonce as a parameter, the script will only know the generated string, not the name of the nonce which is wpdocs-special-string, therefore, my system cannot do check_ajax_referer( 'wpdocs-special-string').

What exactly would be wrong with generating a global nonce so that every AJAX request will be checked against that nonce?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.