Nonces

A nonce is a “number used once” to help protect URLs and forms from certain types of misuse, malicious or otherwise.

Technically, WordPress nonces aren’t strictly numbers; they are a hash made up of numbers and letters. Nor are they used only once: they have a limited “lifetime” after which they expire. During that time period, the same nonce will be generated for a given user in a given context. The nonce for that action will remain the same for that user until that nonce life cycle has completed.

WordPress’s security tokens are called “nonces” (despite the above-noted differences from true nonces) because they serve much the same purpose as nonces do. They help protect against several types of attacks including CSRF, but do not protect against replay attacks because they aren’t checked for one-time use. Nonces should never be relied on for authentication, authorization, or access control. Protect your functions using current_user_can(), and always assume nonces can be compromised.

Why use a nonce?

For an example of why a nonce is used, consider that an admin screen might generate a URL like this that trashes post number 123.

http://example.com/wp-admin/post.php?post=123&action=trash

When you go to that URL, WordPress will validate your authentication cookie information and, if you’re allowed to delete that post, will proceed to delete it. What an attacker can do with this is make your browser go to that URL without your knowledge. For example, the attacker could craft a disguised link on a 3rd party page like this:

<img src="http://example.com/wp-admin/post.php?post=123&action=trash" />

This would trigger your browser to make a request to WordPress, and the browser would automatically attach your authentication cookie and WordPress would consider this a valid request.

Adding a nonce would prevent this. For example, when using a nonce, the URLs that WordPress generate for the user look like this:

http://example.com/wp-admin/post.php?post=123&action=trash&_wpnonce=b192fc4204

If anyone attempts to trash post number 123 without having the correct nonce generated by WordPress and given to the user, WordPress will send a “403 Forbidden” response to the browser.

Creating a nonce

You can create a nonce and add it to the query string in a URL, you can add it in a hidden field in a form, or you can use it some other way.

For nonces that are to be used in AJAX requests, it is common to add the nonce to a hidden field, from which JavaScript code can fetch it.

Note that the nonces are unique to the current user’s session, so if a user logs in or out asynchronously any nonces on the page will no longer be valid.

Customize nonces for guests (non logged-in users)

WordPress core, by default, generates the same nonce for guests as they have the same user ID (value 0). That is, it does not prevent guests from CSRF attacks. To enhance this security aspect for critical actions, you can develop a session mechanism for your guests, and hook to the nonce_user_logged_out filter for replacing the user ID value 0 with another random ID from the session mechanism.

Adding a nonce to a URL

To add a nonce to a URL, call wp_nonce_url() specifying the bare URL and a string representing the action. For example:

$complete_url = wp_nonce_url( $bare_url, 'trash-post_'.$post->ID );

For maximum protection, ensure that the string representing the action is as specific as possible.

By default, wp_nonce_url() adds a field named _wpnonce. You can specify a different name in the function call. For example:

$complete_url = wp_nonce_url( $bare_url, 'trash-post_'.$post->ID, 'my_nonce' );

Adding a nonce to a form

To add a nonce to a form, call wp_nonce_field() specifying a string representing the action. By default wp_nonce_field() generates two hidden fields, one whose value is the nonce and one whose value is the current URL (the referrer), and it echoes the result. For example, this call:

wp_nonce_field( 'delete-comment_'.$comment_id );

might echo something like:

<input type="hidden" id="_wpnonce" name="_wpnonce" value="796c7766b1" />
<input type="hidden" name="_wp_http_referer" value="/wp-admin/edit-comments.php" />

For maximum protection, ensure that the string representing the action is as specific as possible.

You can specify a different name for the nonce field, you can specify that you do not want a referrer field, and you can specify that you want the result to be returned and not echoed. For details of the syntax, see: wp_nonce_field().

Creating a nonce for use in some other way

To create a nonce for use in some other way, call wp_create_nonce() specifying a string representing the action. For example:

$nonce = wp_create_nonce( 'my-action_'.$post->ID );

This simply returns the nonce itself. For example: 295a686963

For maximum protection, ensure that the string representing the action is as specific as possible.

Verifying a nonce

You can verify a nonce that was passed in a URL, a form in an admin screen, an AJAX request, or in some other context.

Verifying a nonce passed from an admin screen
To verify a nonce that was passed in a URL or a form in an admin screen, call check_admin_referer() specifying the string representing the action.

For example:

check_admin_referer( 'delete-comment_'.$comment_id );

This call checks the nonce and the referrer, and if the check fails it takes the normal action (terminating script execution with a “403 Forbidden” response and an error message).

If you did not use the default field name (_wpnonce) when you created the nonce, specify the field name.

For example:

check_admin_referer( 'delete-comment_'.$comment_id, 'my_nonce' );

Verifying a nonce passed in an AJAX request

To verify a nonce that was passed in an AJAX request, call check_ajax_referer() specifying the string representing the action. For example:

check_ajax_referer( 'process-comment' );

This call checks the nonce (but not the referrer), and if the check fails then by default it terminates script execution.

If you did not use one of the default field names (_wpnonce or _ajax_nonce) when you created the nonce, or if you want to take some other action instead of terminating execution, you can specify additional parameters. For details, see: check_ajax_referer().

Verifying a nonce passed in some other context
To verify a nonce passed in some other context, call wp_verify_nonce() specifying the nonce and the string representing the action.

For example:

wp_verify_nonce( $_REQUEST['my_nonce'], 'process-comment'.$comment_id );

If the result is false, do not continue processing the request. Instead, take some appropriate action. The usual action is to call wp_nonce_ays(), which sends a “403 Forbidden” response to the browser.

Modifying the nonce system

You can modify the nonce system by adding various actions and filters.

Modifying the nonce lifetime

By default, a nonce has a lifetime of one day. After that, the nonce is no longer valid even if it matches the action string. To change the lifetime, add a nonce_life filter specifying the lifetime in seconds.

For example, to change the lifetime to four hours:

add_filter( 'nonce_life', function () { return 4 * HOUR_IN_SECONDS; } );

Performing additional verification

To perform additional verification when check_admin_referrer() has found that the nonce and the referrer are valid, add a check_admin_referer action.

For example:

function wporg_additional_check ( $action, $result ) {
    ...
}
add_action( 'check_admin_referer', 'wporg_additional_check', 10, 2 );

For check_ajax_referer() add a check_ajax_referer action in the same way.

Changing the error message

You can change the error message sent when a nonce is not valid, by using the translation system. For example:

function my_nonce_message ($translation) {
    if ($translation === 'Are you sure you want to do this?') {
       return 'No! No! No!';
    } 

    return $translation;
}

add_filter('gettext', 'my_nonce_message');

Additional information

This section contains additional information about the nonce system in WordPress that might occasionally be useful.

Nonce lifetime

Note that just as a WordPress nonce is not “a number used once”, nonce lifetime isn’t really nonce lifetime. WordPress uses a system with two ticks (half of the lifetime) and validates nonces from the current tick and the last tick. In default settings (24h lifetime) this means that the time information in the nonce is related to how many 12h periods of time have passed since the Unix epoch. This means that a nonce made between midday and midnight will have a lifetime until midday the next day. The actual lifetime is thus variable between 12 and 24 hours.

When a nonce is valid, the functions that validate nonces return the current tick number, 1 or 2. You could use this information, for example, to refresh nonces that are in their second tick so that they do not expire.

Nonce security

Nonces are generated using a key and salt that are unique to your site if you have installed WordPress correctly. NONCE_KEY and NONCE_SALT are defined in your wp-config.php file, and the file contains comments that provide more information.

Nonces should never be relied on for authentication or authorization, or for access control. Protect your functions using current_user_can(), always assume Nonces can be compromised.

Replacing the nonce system

Some of the functions that make up the nonce system are pluggable so that you can replace them by supplying your own functions.

To change the way admin requests or AJAX requests are verified, you can replace check_admin_referrer() or check_ajax_referrer(), or both.

To replace the nonce system with some other nonce system, you can replace wp_create_nonce(), wp_verify_nonce() and wp_nonce_tick().

Nonce functions: wp_nonce_ays(), wp_nonce_field(), wp_nonce_url(), wp_verify_nonce(), wp_create_nonce(), check_admin_referer(), check_ajax_referer(), wp_referer_field()

Nonce hooks: nonce_life, nonce_user_logged_out, explain_nonce_(verb)-(noun), check_admin_referer