4

I've some trouble getting nonces working with my ajax submit form.

First of all i create a nonce and pass it to my registered script, i'll later send it to ajax-handler packed with my form fields:

wp_localize_script( 'roll_script', 'Roll', array(
                    'postRollNonce' => wp_create_nonce('nonce-roll')));

In my ajax-response handler i verify the nonce, do my stuff and try to create a new nonce to send back to js, for later submit:

        function on_ajax_roll(){
            if (!wp_verify_nonce($_POST['postRollNonce'], 'nonce-roll' )) die ('No allowed!');
// nonce is valid! do some stuff...     
            $r = array('postRollNonce' => wp_create_nonce('nonce-roll'));           
            $response = json_encode($r);
            header( "Content-Type: application/json" );
            echo $response;
            die();
    }

...but, back to my js, the new nonce is exactly the same as the old one! Since nonce is supposed to change with time, why a second call to wp_create_nonce return the same string?

7

By default, the lifetime of a nonce is one day. The nonce is generated by concatenating a variable representing the current day, the user id, and the name of the action, and hashing the resulting string.

If you want the nonce value to change more frequently, you can filter the 'nonce_life' value. This function, for example, will force nonces to change every hour:

function nonce_hourly() {
    return 3600;
    }
add_filter( 'nonce_life', 'nonce_hourly' );

But this doesn't sound exactly like what you're trying to do, either. You may have better luck generating the kind of one-time nonces you want by using a different name for the "action" value of the nonce, one that will be truly unique to the specific action you're trying to perform. It looks as though you're using "nonce-roll" as the action name for some distinct actions that you want to be able to check separately — maybe you can use a more specific action name for each action you're trying to perform and authorize.

  • ok, now it's definitively clear! tnx allot! – Gabriele B Apr 14 '11 at 19:30
  • Does this mean we can't use the wp nonce to generate a CSRF token for users who are not logged in as WordPress users? – Adam Apr 11 '17 at 14:16
  • Think I've got my own answer. Guess i need something from session and nonce_user_logged_out – Adam Apr 11 '17 at 14:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.