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!
1 Answer
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' );