Categories
Web Development WordPress

WordPress: How to Use Nonces to secure AJAX calls

This article assumes you have knowledge of PHP, JQuery, developing for WordPress and enqueueing scripts and using AJAX calls that work but do not use nonce security.

I am not here to try to sell you on using nonces. Nonces do add security to AJAX calls but they are not REQUIRED, just greatly recommended. WordPress describes nonces as “a one-time token generated by a website… This could prevent unwanted, repeated, expired, or malicious requests from being processed.”

In other words, a nonce is a unique key that your website creates that allows you to verify actions. For the purposes of this article, we’re going to focus on using nonces to ensure that requests are originating from our own website.

First, let’s start by generating the nonce. The proper way of doing this is by localizing your javascript files in the PHP where you register and enqueue the script files.

wp_register_script( 'cp_script', plugin_dir_url( __FILE__ ) . '/library/js/cp_script.js', [ 'jquery' ], 'all', true );

		wp_localize_script( 'cp_script', 'vars', [
			'ajaxurl' => admin_url( 'admin-ajax.php' ),
			'nonce'   => wp_create_nonce('any_text'),
		] );

		wp_enqueue_script( 'cp_script' );

In the code above we register a script, point to it’s file, tell WordPress jquery is a dependency, and then localize into the script 1) the ajax url and 2) the nonce that we generate

Then inside the script file, create a JQuery on click function and inside it put this AJAX call:

jQuery.ajax({
	type: 'POST',   // Adding Post method
	url: cp_script.ajaxurl, // Including ajax file
	data: {
	 "action": "my_function",
	 "data"   : data,
	 "nonce": cp_script.nonce
	},
	success: function( response ) { // Show returned data using the function.
		alert( response );
	}

The final step is the shortest. Inside of my_function, the function being called by the AJAX call, just add the actual check as it’s first line:

function my_function() {
     check_ajax_referer( 'any_text', 'nonce' );
...

The check is just that one line. Notice ‘any_text’ can be subbed for any string you choose as long as it matches the string used in the function to generate the nonce, and ‘nonce’ can also be any variable name, as long as it matches the parameter passed in the data of the AJAX call.

Happy WordPressing!

Sources:

How to Add a WordPress AJAX Nonce

Leave a Reply