How to Restrict Anonymous Access to the WordPress REST API?

The WordPress REST API is a powerful feature that allows developers to interact with site data via HTTP requests. However, by default, the WordPress REST API exposes many endpoints to the public. This means that even unauthenticated anonymous users can read information such as posts, pages, and even the system’s registered user list.

Exposing data like the user list can be leveraged by malicious attackers for brute-force password cracking or spamming (username enumeration attacks). Therefore, for security reasons, many sites need to restrict or completely disable anonymous access to the REST API. This article will introduce several effective methods.

Why Restrict Anonymous Access to REST APIs?

  • Prevent Username Enumeration: The default /wp-json/wp/v2/users endpoint exposes the site’s usernames and author IDs. This is one of the most common security vulnerabilities.
  • Prevent Content Scraping: Attackers can easily batch-fetch your post content via the API, including private drafts or custom post types.
  • Reduce Server Resource Consumption: Restricting unnecessary API requests can lighten the server load and help defend against lightweight CC attacks.
  • Protect Sensitive Data: If your site has custom REST API endpoints, you might unintentionally leak non-public data records.

This is the most common and secure approach. By using the rest_authentication_errors hook, we can intercept all API requests. If a request comes from an unauthenticated visitor, it returns an unauthorized error. This way, only logged-in users (or requests providing valid credentials like Application Passwords) can access the API.

Add the following code to your current child theme’s functions.php file:

add_filter( 'rest_authentication_errors', function( $result ) {
    # If there is already another authentication error status, return it directly
    if ( true === $result || is_wp_error( $result ) ) {
        return $result;
    }

    # If the current user is not logged in, deny access
    if ( ! is_user_logged_in() ) {
        return new WP_Error(
            'rest_not_logged_in',
            __( 'You are currently not logged in. Access to the REST API is prohibited.', 'your-text-domain' ),
            array( 'status' => 401 )
        );
    }

    return $result;
});

Code Logic Analysis: When a REST API request is received, WordPress triggers this filter. The code checks is_user_logged_in(). If not logged in, it throws a WP_Error with a 401 Unauthorized status code. Since the request is intercepted at a very early stage, it effectively avoids subsequent database query consumption.

Method 2: Limit to Removing Sensitive Endpoints (e.g., /users)

Completely disabling anonymous access can have side effects. If your theme or plugins (e.g., certain form plugins with Ajax submission, headless frontends built on React/Vue, etc.) rely on the public REST API, globally disabling it will cause them to fail. In this case, you can choose to keep most APIs and only remove or modify the most sensitive /users endpoint.

add_filter( 'rest_endpoints', function( $endpoints ) {
    # Remove the default users collection endpoint and individual user endpoint
    if ( isset( $endpoints['/wp/v2/users'] ) ) {
        unset( $endpoints['/wp/v2/users'] );
    }
    if ( isset( $endpoints['/wp/v2/users/(?P[\d]+)'] ) ) {
        unset( $endpoints['/wp/v2/users/(?P[\d]+)'] );
    }
    return $endpoints;
});

This code uses the rest_endpoints filter to directly unregister user-fetching routes. Neither anonymous guests nor logged-in administrators can fetch the user list through this endpoint. If you need to use this endpoint in the backend, you can combine it with current_user_can( 'list_users' ) checks before deciding whether to unset.

Method 3: Use Security Plugins to Implement Control

If you don’t want to manually modify the code, using existing WordPress security plugins to restrict REST API access is also a convenient method:

  • Disable REST API: This is a very lightweight free plugin specifically designed to restrict the REST API. You can configure it to completely disable anonymous access or whitelist specific endpoints (e.g., allowing Contact Form 7 endpoints).
  • Wordfence Security / iThemes Security: If you have already installed these mainstream security plugins, they usually include features like “Disable anonymous REST API access” or “Disable User Enumeration” in their settings.

Summary

On most traditional WordPress sites used for displaying information, restricting anonymous access to the REST API is a highly recommended security hardening measure. For general site owners, it is recommended to use Security Plugins or Method 1 for global restrictions. If your site is complex or the frontend functionality relies on the API, proceed with caution, test thoroughly, and then choose Method 2 to partially restrict and filter sensitive routes.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *