

Learn how to disable the REST API in your WordPress site for logged-out users and build safer WordPress websites.
function disable_rest_api_for_guests($access) {
if(!is_user_logged_in()) {
return new WP_Error(
'rest_disabled',
__('The REST API is disabled for guests.'),
array('status' => 403)
);
}
return $access;
}
add_filter('rest_authentication_errors','disable_rest_api_for_guests');
Follow these simple steps to disable REST API access for guests:
That’s it! REST API access is now disabled for non-logged-in users on your WordPress site.
The WordPress REST API introduces several security concerns when left accessible to unauthenticated users. The main issue is that the /wp-json/ endpoint reveals critical site information to anyone, authenticated or not. When visitors access this endpoint, the WordPress API exposes which plugins and themes use the RESTful API, available custom post types, and potentially sensitive details about your site structure.
This information provides hackers with a blueprint to identify and target vulnerabilities in your plugins, themes, or core WordPress installation.
Cross-Site Scripting (XSS) attacks are possible when API endpoints fail to properly sanitize user input, allowing attackers to inject malicious scripts through API requests. SQL injection vulnerabilities occur when API endpoints interact with the database without validating incoming requests, letting attackers embed harmful SQL commands within API calls.
Authentication bypass represents a critical flaw where the REST API can circumvent other security measures like Two-Factor authentication and reCAPTCHA. This creates a scenario where your front door has multiple locks, but a window remains open that only becomes apparent when someone probes for vulnerabilities.
Despite these security concerns, the WordPress REST API offers significant benefits for modern development. It allows external applications to interact with WordPress sites programmatically, allowing access, updates, and remote content management.
The REST API is particularly valuable for headless WordPress setups, where WordPress serves as a content management backend while the frontend is built with modern JavaScript frameworks like React, Vue.js, or Angular.
Disabling REST API access for guests prevents the API from bypassing authentication measures protecting your website. When you require admin privileges, you protect against anonymous users accessing data.





