What is CSRF?

Cross-Site Request Forgery (CSRF) is an attack that forces an authenticated user to execute unwanted actions on a web application they are currently logged into. With a little social engineering (such as a phishing email or a malicious link), an attacker can trick a WordPress administrator into unknowingly submitting a request that alters the site’s state. Because the browser automatically includes the admin's session cookies, the WordPress application treats the malicious request as legitimate.

CSRF Scenarios in WordPress

In WordPress, CSRF attacks target administrative functionalities. For instance, an attacker might craft a hidden form on an external website that sends a request to http://your-site.com/wp-admin/user-new.php to create a new admin user. If a real administrator visits the attacker's site while logged into their own WordPress dashboard, the form submits silently in the background. The WordPress server receives the valid session cookie and creates the malicious account without the admin's conscious consent.

Preventing CSRF with Nonces

WordPress has a powerful built-in defense mechanism against CSRF called Nonces (number used once). To defend your site:

  • Generate Nonces in Forms: Use wp_nonce_field() inside your custom HTML forms or backend settings pages. This generates a unique, time-sensitive cryptographic token tied to the user's current session.

  • Verify Nonces on Processing: When processing form submissions or AJAX requests, always validate the token using check_admin_referer() or wp_verify_nonce(). If the token is missing or invalid, reject the request immediately.

  • Log Out Safely: Always use the default WordPress logout links, which include nonces, preventing attackers from forcing users to log out unexpectedly.

  • Educate Site Administrators: Advise users to avoid browsing other websites in the same browser session where they have an open WordPress admin dashboard.