Contents
What is CSRF Attack?
CSRF ( Cross Site Request Forgery ) attack is an attack technique capable of impersonating a user to perform unwanted activities on a website or application.
A CSRF attack has the potential to have serious consequences for users or businesses, such as password change, data theft, sabotage, etc.
To prevent a CSRF attack scenario, WordPress has a mechanism to combat this problem using Nonce.
So, what is WordPress Nonce?
WordPress Nonce or Nonce is a random string of characters attached to a URL or form to verify that the action was performed by the user.
This string is used once and is different for each user. That means it can’t be faked. If the nonce is invalid, WordPress will reject the request.

Diagram showing how nonce works
How to deploy WordPress Nonce?
There are 3 ways to create a WordPress Nonce:
-
wp_create_nonce()– Create a simple nonce, use whatever you want. -
wp_nonce_url()– Add a_wpnonceparameter to the URL path. -
wp_nonce_field()– Creates a hidden input field containing the nonce.
For example:
<?php $new_nonce = wp_create_nonce( 'add_product' ); // zxcvbn678 $url = 'https://hocwordpress.vn/'; $nonce_url = wp_nonce_url( $url, 'delete_product' ); // https://hocwordpress.vn/_wpnonce=zxcvbn678 wp_nonce_field( 'change_password' ); // <input id="_wpnonce" name="_wpnonce" type="hidden" value="zxcvbn678" /><div> <span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span><span>10</span><span>11</span> </div>
To verify the nonce, we use the wp_verify_nonce() function
The example below handles form submission – submit form.
<?php $nonce = $_POST['_wpnonce'];
if( wp_verify_nonce( $nonce, 'change_password' ) ) {
// Thành công, tiến hành thay đổi password
// ...
} else {
return false; // Huỷ bỏ
}
<div><span>1</span><span>2</span><span>3</span><span>4</span><span>5</span><span>6</span><span>7</span><span>8</span><span>9</span>
summary
CSRF is the most common vulnerability found in WordPress plugins and themes. Through this article, I hope I have helped you prevent a CSRF attack in the future.
If you find it interesting, you can follow the wordpress tips section to know more new knowledge.
Follow fanpage to receive the latest posts: Group
Wish you have interesting and interesting knowledge about wordpress!

