WordPress CSRF Attacks: Vulnerability and Prevention


prevent WordPress CSRF attacks

All attacks are bad for your site, but WordPress CSRF attacks are damaging on multiple levels. This class of attacks hijacks the account of an authenticated user to steal data, change settings or permissions, and in general cause havoc. 

WordPress site administrators need to be particularly vigilant about CSRF vulnerabilities found in the plugins on their sites. Therefore, the best defence is to have a WordPress firewall to protect hackers from exploiting vulnerabilities.

In this article, we will explain exactly what a WordPress CSRF attack means, and how to prevent hackers from taking advantage of vulnerabilities. 

TL;DR: The best defense against CSRF attacks is to use a security plugin like MalCare. MalCare’s scanner will detect any malware on your site in minutes, and you can use the activity log to monitor the actions of logged-in users. Apart from that, MalCare has the best WordPress firewall, which will protect your site from a wide swathe of attacks.  

What is WordPress CSRF? 

A CSRF attack in WordPress is when a hacker exploits a CSRF vulnerability on your site, and hijacks the account of a logged-in user. The hacker accomplishes this attack by tricking the user into visiting a malicious website. Once the unwitting user is on the malicious site, a script is executed, sending a request to the vulnerable WordPress website from the user’s browser. Since the user is already logged in, your site assumes that the request is genuine, originating from the authenticated user.

It’s important to note that CSRF attacks rely on the session data stored in the user’s browser cookies. This data is included with the malicious request, making it appear as if it is coming from a legitimate user. As a result, your site processes the request, unaware that it is initiated by an attacker.

By utilizing the user’s active session, these attacks exploit the privileges and permissions associated with their account. This means that an attacker could potentially access restricted areas or perform actions on the user’s behalf, depending on their privileges.

Using a WordPress firewall to block malicious requests from exploiting vulnerabilities is an important safeguard for sites.

☣️ To illustrate this further, let’s consider a couple of scenarios where CSRF attacks might be employed. First, an attacker may use a CSRF attack to initiate transactions using the victim’s stored payment information or other sensitive data. Alternatively, they could modify the victim’s login credentials, granting the attacker direct access to the user’s account. If the logged-in user is an admin, the attacker now has complete access to your site and can create havoc as a result. 

How to check for a CSRF vulnerability in WordPress?

To stay ahead of CSRF vulnerabilities in WordPress plugins, it’s crucial to stay informed. If your site has MalCare installed, you will receive an email any time a plugin has a vulnerability. That’s your cue to update it right away, and run a scan for good measure.  

Alternatively, you can also stay updated on vulnerabilities through the WordPress community. Engage with security forums, discussion boards, and mailing lists dedicated to WordPress security, where experts share insights and best practices. Monitor official plugin forums and support channels for vulnerability announcements and security updates.

Regularly check a WordPress vulnerability database for known vulnerabilities in plugins and themes.

Stay updated on emerging WordPress CSRF-related risks, affected plugin versions, and available fixes. Subscribe to reputable security blogs and newsletters that cover WordPress security to receive timely alerts about vulnerabilities and recommended mitigation techniques.

WordPress CSRF Protection

There are effective strategies and best practices to fortify your site’s defenses against WordPress CSRF vulnerabilities. 

1. Install a security plugin with a firewall 

One of the best defenses your WordPress site can have is a firewall. A firewall is like a forcefield, blocking attacks and bad requests before they reach your site. A good firewall will not only protect your site from hackers exploiting vulnerabilities but also markedly improve its performance as a direct consequence. 

MalCare has the most advanced firewall for WordPress sites, with real-time updates, bot protection against malicious bots, and a global IP network that proactively safeguards your site. Install MalCare for a great and reliable defense against CSRF attacks and other threats. MalCare also has a top-notch malware scanner, malware removal functionality, and a great vulnerability scanner. There are also a tonne of other useful features like an activity log that can alert you to unusual or suspicious activity from logged-in users. 

2. Keep everything up to date 

95% of hacks occur because of vulnerabilities in plugins and themes, and a lot less often in the WordPress core itself. 

The key to minimizing damage from vulnerabilities is to keep everything on your site updated. Outdated software can have known vulnerabilities that attackers can exploit. Check out our comprehensive guide on safely updating your WordPress site for detailed instructions.

💡 MalCare has a vulnerability scanner that can help you keep track of which plugins and themes have vulnerabilities, and need to be updated without delay.

3. Use anti-CSRF plugins for forms

A potential vulnerability are various forms, like your comment form. The best way to combat it is to use a plugin like Comment Form CSRF plugin. It will add a secret token to your comment form that can be authenticated. It’s also an easy to setup using the following steps:

  • Go to your wp-admin panel and look for the Comment Form CSRF plugin in the directory. 
  • Click install when you find it
  • Once the install is done, click Activate. 

This will automatically add tokens to your comment forms with no additional steps. You’re good to go. 

4. Be cautious about clicking links 

Exercise caution when clicking on links, particularly if you are a site admin. Avoid clicking on suspicious or unverified links, as they can lead to CSRF or phishing attacks.

When in doubt, use extra vigilance and verify the authenticity of the source before proceeding. As a rule of thumb, it is always better to type a URL in the address bar directly, rather than click on a link. This small adjustment in your browsing behavior can prevent attacks from being successful. 

5. Implement CSRF-specific protective measures

Apart from the other protective measures we’ve mentioned, there are some that are designed to specifically fight CSRF attacks. If you have development expertise, you can also add them directly to your site. While these methods are not foolproof, they significantly reduce the risk. We do recommend having a WordPress developer implement these, and ensure you backup your site

Use WordPress CSRF tokens

WordPress CSRF tokens are like secret codes that web applications use to protect against sneaky hackers. They’re unique and random, kind of like lottery numbers. One of the most popular types of CSRF tokens is a nonce. 

Nonces, short for “number used once,” are unique tokens that verify the authenticity of requests. They’re a string of numbers that are unique to a user session and can be added to either forms or URLS. 

A default WordPress site already uses nonces but you can use it in custom code like custom forms, or plugins for example. This also means that using nonces requires some coding knowledge. Nonces are especially useful to make sure that only valid users can make changes to your site. For example, you can use it to authenticate that the user trying to delete a comment is an admin.

Now, let’s talk about how to use them. You can either add predefined nonce functions that WordPress has, or you can create custom ones. There will also be at least two snippets of code that you need to use—one to generate a nonce and another to verify the nonce that is generated. 

In the following example, we will demonstrate how to use nonces to authenticate a user session in a custom contact form. 

  1. Generate a nonce:
    You need to add the nonce before the data entered into the form is saved to the database. Therefore you will need to add the following code just before the section that renders the form fields on your site.  
<?php wp_nonce_field( 'my_custom_contact_form_nonce', 'my_custom_contact_form_nonce' ); ?>

This way, every time the form is filled, the nonce is sent along with the data.

  1. Verify the nonce: Once the nonce is sent alongside the data, you now need to verify it to authenticate the user. You will now need to add a snippet before the section that processes the form submission. Here is an example code snippet that needs to be added to the functions.php file, in the form handler function:
function my_custom_contact_form_handler() {

    // Check if the nonce is valid

    if ( ! wp_verify_nonce( $_POST['my_custom_contact_form_nonce'], 'my_custom_contact_form_nonce' ) ) {

        // Nonce is not valid, show an error message or redirect to an error page

    } else {

        // Nonce is valid, process the form submission



  1. Customize the user experience: You can add a lot of customization around the nonce, like the message that appears if the nonce verification fails. Here’s an example:
if (wp_verify_nonce($_POST['contact_form_nonce'], 'contact_form_nonce_action')) {

            // Nonce verification successful, process the form

            $name    = sanitize_text_field($_POST['contact_form_name']);
            $email   = sanitize_email($_POST['contact_form_email']);
            $message = sanitize_textarea_field($_POST['contact_form_message']);

            // Perform further validation and processing of the form data

            // ...

            // Display success message

            echo '<p>Thank you for your message! We will get back to you soon.</p>';

        } else {

            // Nonce verification failed, display error message

            echo '<p>Error: Goodbye hackers! Better luck next time. </p>';



Use SameSite cookies 

SameSite cookies are a type of HTTP cookie attribute that provides additional security and privacy measures. It allows a web server to dictate how cookies should be handled by the browser when making cross-site requests. It works by ensuring that cookies are only sent in same-site requests, preventing unauthorized third-party websites from executing actions on behalf of the user. 

Imagine you own a website that sells shoes called ShoeWorld. Your site allows users to log in to see their purchase history, and store their payment data.  Because you want to protect your users from CSRF, your site adds SameSite cookie attributes to the user’s browser. 

The SameSite cookie is a special tag that adds itself to a logged-in user’s session. The tag tells the user’s browser to only add the ShoeWorld cookie to a response to a request from ShoeWorld, not any other site. This ensures that the associated session data is sent exclusively to ShoeWorld.

Therefore, a hacker cannot use their malicious site to force the user’s browser to send a request to ShoeWorld, because the request originated from the malicious site, not ShoeWorld. 

There are 3 ways to implement the SameSite cookie attribute: 

  • SameSite=None: With this rule, your website allows the user’s browser to send cookies, even when they click on a link to another website. This allows them to stay logged in when navigating between your website and other sites. The None setting is generally used when you want to allow data from your site to be visible elsewhere. An example of this is a Twitter or Instagram widget on a personal or corporate blog. However, when using None, the website must ensure that the cookies are securely transmitted over HTTPS, and include the “Secure” attribute to prevent unauthorized access.
  • SameSite=Strict: If sensitive user session data is stored in a cookie, then SameSite=Strict is a better bet. The browser will only send the cookie when the user is actively browsing within the same website. If the user clicks on a link that takes them to a different website, your browser won’t send the cookie along. 
  • SameSite=Lax: With SameSite=Lax, the browser will send the user’s session cookie when they click on a link within the same domain. However, if the user clicks on a link that takes them to an external website, such as an article shared by someone, your browser won’t include the session cookie. This prevents the external website from accessing your session information and helps protect the user’s account from attacks. 

The easiest way to implement SameSite cookies is to use a plugin. 

1. Install and activate SameSite CSRF plugin: Hover over Plugins in your wp-admin sidebar. Then, click Add New. Search for the SameSite CSRF plugin and click on Install and then Activate

SameSite Cookies

2. Configure SameSite settings: The plugin enables you to configure ameSite cookie settings. You can then add the piece of code to your site’s wp-config.php file.

To do that, access your files using File manager or an FTP client like Cyberduck.

Then, open the root folder. Quite often, the folder is called public_html or www. Find the wp-config file, open to edit, and add the following lines: 

define( ‘WP_SAMESITE_COOKIE’, ‘Lax’ ); // 

/** Sets up WordPress vars and included files. */

require_once(ABSPATH . 'wp-settings.php');

The code has to be added just above /** Sets up WordPress vars and included files. */ line in the file. You can also change ‘lax’ to strict or none as you please. We recommend keeping the rules strict, unless you have a very specific use case. 

Use referrer-based validation

Let’s say you have an ecommerce site that accepts reviews. When a customer submits a product review, the hidden referrer field captures the URL of the page where the review form was accessed. The server verifies that the referrer matches the website’s domain, ensuring the review comes from a legitimate source. It is used on certain resources or actions and blocks access based on the referring source of a request.

Referrer-based verification involves examining a particular security header in an HTTP request to determine if the request originates from an allowed or expected source. 

Security headers are directives issued by web servers to browsers for security purposes. They are sent via HTTP requests, and control various aspects of security. The referer header, which is specifically relevant to CSRF attacks, is a security header.  

The referer header indicates the URL of the webpage that is requesting a resource. It helps web servers track the source of incoming requests and provides information about the user’s browsing context. 

We’re using the HTTP Headers plugin to implement referrer-based validation:

HTTP Headers

  1. Install and activate the HTTP Headers plugin: In the Plugins page of your WordPress dashboard, click Add New. Then, search for HTTP Headers in the search bar. Click Install and then Activate.
  2. Access the settings: Then, click Settings in the sidebar and click HTTP Headers. Then, click Security. Click the Edit button beside Referrer-Policy.
  3. Configure the settings: Click On and pick one of the following options from the dropdown menu: 
HTTP Headers settings
  • no-referrer: This policy does not send the Referer header at all. It provides the highest level of privacy but also removes referrer information entirely, including when navigating within your own website. This configuration may not be suitable for scenarios that rely on referrer information for legitimate functionality.
  • no-referrer-when-downgrade: It omits the referrer header when navigating from an HTTPS site to an HTTP site, but sends it otherwise. This helps protect sensitive information when transitioning from a secure to an insecure connection.
  • origin: The origin refers to the combination of the scheme (HTTP or HTTPS), domain, and port number. Consider the URL: https://www.example.com:8080/path/page.html
    The origin would be: https://www.example.com:8080

    This policy sends only the origin part of the referrer URL, without including any path, query parameters, or fragment identifier. It is sent for both same-origin and cross-origin requests. This helps protect sensitive path, query, or fragment data in both types of requests while preserving the necessary origin information.
  • origin-when-cross-origin: When making a same-origin request within the same protocol level (HTTP to HTTP, HTTPS to HTTPS), include the origin, path, and query string in the request. Web pages are considered to be from the same origin if they share the same domain, protocol, and port. For cross-origin requests and requests to less secure destinations (HTTPS to HTTP), include only the origin.
  • same-origin: This policy includes the referrer information only when the request is made from the same origin as the target resource. It excludes the referrer when the request is made from a different domain or subdomain. This configuration helps protect against CSRF attacks by not including referrer information for cross-origin requests. This is our recommendation. 
  • strict-origin: This policy sends the full referrer URL when navigating within the same site or to a subdomain, but excludes it for cross-origin requests. It offers some protection against CSRF attacks while preserving referrer information within the same site.
  • strict-origin-when-cross-origin: This policy is the default setting and sends the full referrer URL when navigating within the same site or to a subdomain. For cross-origin requests, it includes only the origin part of the referrer URL. This configuration balances security and functionality by limiting the exposure of sensitive information in cross-origin requests.
  • Unsafe-url: This is the worst one. It sends all your information, origin and all, to anybody that asks. It has no filter for unsafe URLs. 
  1. Finish configurations: Click Submit when you’re done. You’re good to go. Your security header settings have now been set.

As you may have discovered, WordPress CSRF-specific measures can be geared towards developers. So, either hire a developer to take care of it for you or gear up for a lot of technical jargon. 

What to do if your website has a CSRF vulnerability?

Discovering that your site has been made vulnerable to WordPress CSRF attacks can be a cause for concern. But here are two crucial steps to follow if you suspect or have confirmed a CSRF vulnerability:

  1. Update the vulnerable plugin or theme: The first and most critical action is to update the plugin or theme that has the vulnerability as soon as possible. Check for updates from the plugin or theme developer and install the latest version, which will typically include patches and fixes. By updating the vulnerable component, you effectively close the door that CSRF attacks can exploit, enhancing the overall security of your site.
  2. Force log out users: Force log out all users from your WordPress site. This step is essential because CSRF attacks leverage active user sessions to perform unauthorized actions. By ending all active sessions, attackers cannot hijack user sessions. Plus, by forcing users to log back in, you ensure that any existing WordPress CSRF tokens tied to compromised sessions become invalid, reducing the risk of further exploitation.

    You can use MalCare’s hardening options to force logout users, and reset security keys in one move.

    Alternatively, as there is no in-built feature to force log out users, you can install a plugin like WPForce Login. This action will prompt users to reauthenticate themselves, creating new sessions with updated security measures.
WPForce Logout

How does a CSRF attack work?

Let’s talk about what happens to a site during a CSRF attack. In this section, we’ll break it down to basics and show you how a CSRF attack works.

Understanding HTTPS Requests

Hypertext Transfer Protocol Secure (HTTPS) is a secure version of HTTP that encrypts data transmitted between a user’s browser and a web server. When a user makes an HTTPS request, the data is encrypted, ensuring confidentiality and integrity. This applies to both logged-in and non-logged-in users, as encryption is maintained throughout the communication.

When a logged-in user sends a GET or POST request, the request is authenticated. The website uses cookies to identify the logged in user. IF a user isn’t logged in, there are no security concerns.

Understanding the role of cookies

Cookies are commonly used for session management and user authentication. When a user logs into a website, the server generates a unique session ID and sets it as a cookie in the user’s browser. Subsequent requests from the user include the cookie, allowing the server to identify the user and maintain their session. For logged in users, cookies play a crucial role as they carry the session information needed to authenticate requests. Without the proper cookie, the server may reject or redirect the request to the login page. This is what CSRF attacks exploit. 

Behind CSRF attacks

There are two aspects to it: site side and user side. We’ve talked about both here:

  • User side: Let’s say a user is logged into goodwebsite.com. The hacker lures them onto another site called badwebsite.com. This could be because of a totally unrelated vulnerability. It could be a button that was added by the hacker or even mails sent by the hacker. The user is then lured into clicking a button or image – sending a request. The hacker has already added HTML code to send these requests to goodwebsite.com. Keep in mind that the user is logged into goodwebsite.com on the same browser. 
  • Website side: The website tries to authenticate the request and accepts it. The website recognises that the user is logged in and the browser cookies are authentic. So, there is no reason to suspect that the request is from a hacker. Unfortunately, the request is malicious code. For example, the request could be to change the password of the user. This allows the hacker to login to the user’s account using the new password they’ve created and access your site. This is especially dangerous if the user is an admin. 

What is the impact of CSRF vulnerabilities?

CSRF attacks pose a significant threat, not only to users, but also to WordPress sites. 

Impact on users

CSRF attacks can have detrimental consequences for users, compromising their security and privacy. These attacks exploit the trust between a user’s browser and a website, leading to potential theft of user details and credentials. Attackers can trick users into unknowingly performing actions that disclose sensitive information or perform unauthorized transactions. This can result in financial losses, identity theft, and exposure of personal information. CSRF attacks pose a significant threat to users’ trust in online platforms and their overall digital well-being.

Impact on sites

CSRF attacks can be highly dangerous for WordPress sites, exposing them to various risks and compromising their integrity. Attackers can exploit CSRF vulnerabilities to install malware, potentially affecting the entire site and its visitors. This can lead to the injection of malicious code, unauthorized access to secure areas, and the compromise of sensitive data.

If an attacker gains control over an admin account through CSRF, they can exploit the site, manipulate its content, gain access to user information, and even take complete control over the site. The consequences include reputational damage, financial loss, legal implications, and erosion of user trust. Protecting against CSRF attacks is vital to safeguard the site’s reputation, maintain user confidence, and ensure the security of data and resources.

Manipulating your site

CSRF attacks focus on manipulating target websites rather than directly retrieving sensitive information such as admin credentials or financial data. As these attacks are initiated through a user’s browser, the response is also sent back to the same browser, making the accessed data inaccessible to the attacker. Instead, the primary objective of a hacker launching a CSRF attack is to carry out unauthorized actions, such as modifying content or settings on the targeted website.

Final thoughts 

When looking to protect your WordPress site from CSRF attacks, your strategy should be two-fold: install a strong WordPress firewall like MalCare, and keep everything on your site updated. 

MalCare’s advanced firewall provides comprehensive protection against WordPress CSRF attacks and offers a range of powerful security features to fortify your WordPress site. 


Does WordPress use CSRF? 

Yes, WordPress can be vulnerable to CSRF attacks. To prevent CSRF attacks, you can implement measures such as using CSRF tokens, verifying referrer headers, and employing security plugins that offer a great firewall for protection. MalCare is a security plugin with a best-in-class firewall that is easy to install. 

Is CSRF possible with HTTPS? 

Yes, CSRF attacks can occur regardless of whether your site uses HTTPS (SSL). While HTTPS encrypts data transmission, it does not inherently prevent CSRF attacks. Additional measures, such as implementing CSRF tokens, are necessary to protect against CSRF vulnerabilities.

Is CSRF the same as cross-site scripting (XSS)? 

No, CSRF and XSS are distinct security vulnerabilities. CSRF involves exploiting a user’s authenticated session to perform unauthorized actions, while XSS allows an attacker to inject malicious scripts into a website to manipulate user interactions or steal data.

How do I prevent CSRF in WordPress? 

To prevent CSRF attacks in WordPress, you can:

  • Implement CSRF tokens in forms 
  • Validate referrer headers to ensure requests originate from your site.
  • Utilize security plugins specifically designed to mitigate CSRF vulnerabilities.
  • Regularly update WordPress, themes, and plugins to patch security vulnerabilities.

What is the impact of a CSRF vulnerability on WordPress? 

A CSRF vulnerability can have various impacts on a WordPress site. It can allow attackers to perform actions on behalf of authenticated users, such as changing passwords, making unauthorized transactions, or modifying user settings. The severity of the impact depends on the privileges and permissions associated with the targeted user’s account.

Why are CSRF attacks difficult to detect? 

CSRF attacks can be challenging to detect because they exploit the trust between a user’s browser and a website. The malicious requests sent by attackers appear legitimate, as they carry the user’s session data. Without proper protection mechanisms such as CSRF tokens or security plugins, distinguishing between legitimate and malicious requests becomes difficult.

How is a CSRF attack detected? 

Detecting CSRF attacks typically involves monitoring and assessing vulnerabilities on platforms or utilizing security plugins. Security plugins designed to combat CSRF vulnerabilities can scan your WordPress site, analyze form submissions, and identify potential vulnerabilities. Regular security testing and penetration testing can also help identify and mitigate CSRF attack vectors.

Why do CSRF attacks happen? 

CSRF attacks occur when an attacker tricks a logged-in user into unintentionally executing a malicious action on a targeted website. These attacks exploit the trust placed in the user’s browser session to perform unauthorized actions on the user’s behalf. The motivation behind CSRF attacks can vary, including financial gain, unauthorized access, or data manipulation.

What is the plugin for CSRF protection in WordPress? 

While WordPress itself does not have a specific plugin dedicated solely to WordPress CSRF protection, security plugins like MalCare, along with plugins that provide CSRF protection for specific elements such as Comment Form CSRF protection and SameSite Cookies, can enhance the security of your WordPress site against CSRF attacks.

How do I enable CSRF protection? 

Enabling CSRF protection in WordPress requires implementing security measures such as:

  • Using CSRF tokens in forms .
  • Verifying referrer headers to ensure requests originate from your site.
  • Employing security plugins that offer CSRF protection features.
  • Following security best practices and regularly updating WordPress, themes, and plugins to address known vulnerabilities.



You may also like

dns hijacking
DNS Hijacking: All You Need to Know About It

Have you ever typed a familiar URL into your browser only to land on a strange, unfamiliar website? Imagine your visitors facing the same dilemma when accessing your website. They…

How to Protect Your Website from Hackers
How to Protect Your Website from Hackers

Every day, small businesses become victims of cyber attacks. Hackers break into websites, steal customer data, and damage reputations. Your website, which is vital for your business, is at risk…

What are Website Backdoors and How to Clean Them?
What are Website Backdoors and How to Clean Them?

Are you frustrated with your website getting hacked again and again, even after you’ve cleaned it each time? You’ve spent hours fixing your site, only to find that the problem…

How can we help you?

If you’re worried that your website has been hacked, MalCare can help you quickly fix the issue and secure your site to prevent future hacks.

My site is hacked – Help me clean it

Clean your site with MalCare’s AntiVirus solution within minutes. It will remove all malware from your complete site. Guaranteed.

Secure my WordPress Site from hackers

MalCare’s 7-Layer Security Offers Complete Protection for Your Website. 300,000+ Websites Trust MalCare for Total Defence from Attacks.