Reduce nonce lifespan

The question:

for a personal plugin (nothing going to the public or commercial), I built an AJAX form and its endpoint is a custom endpoint (REST Api).

When a certain Page containing my form is accessed, I generate a nonce.

Then, the user sends the form, I add the conventional header (X-WP-Nonce) and in the endpoint function I validate the nonce I first created when the page was loaded.

I would like my nonce to be short-lived, that is, 12 hours is too much.

I found I can use apply_filters('nonce_life', timeHere) but I don’t know where this line is supposed to be: should it go right before this one?

$nonce = wp_create_nonce('wp_rest');

Moreover: could this line change the lifespan of ANY nonce in my WP or does the change affect only my nonce? I wouldn’t want to break other plugins.

Thanks!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Yes, using that filter will affect the lifespan of all nonces created after this filter is added, and while it remains in-place. So your best bet is to add it, create the nonce, remove it:

    function my_nonce_lifetime() {
        return 600; // 10 minutes
    }
    add_filter( 'nonce_life', 'my_nonce_lifetime' );
    $nonce = wp_create_nonce( 'wp_rest' );
    remove_filter( 'nonce_life', 'my_nonce_lifetime' );

EDIT:
As suggested by someone in the comments, you’ll need to use the same filter later on when you’re verifying the nonce, as below:

    add_filter( 'nonce_life', 'my_nonce_lifetime' );
    wp_verify_nonce( $your_nonce_value, 'wp_rest' );
    remove_filter( 'nonce_life', 'my_nonce_lifetime' );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment