Disable the REST API for unauthorized users
WordPress’ REST API is accessible to all visitors by default. Among other things, this can be used for something called “enumerating usernames” and can be seen as a security risk. This particular risk is known as CVE-2017-5487.
You can easily check if your website is vulnerable to this by visiting the following URL in an incognito window: https://<domainname.com>/wp-json/wp/v2/users/.
Are you getting an error message like the one below? Then WordPress’ REST API is already secured and you don’t need to read any further.
{"code":"itsec_rest_api_access_restricted","message":"You do not have sufficient permission to access this endpoint. Access to REST API requests is restricted by Solid Security settings.","data":{"status":401}}
{"code":"rest_not_logged_in","message":"Je bent momenteel niet ingelogd.","data":{"status":401}}
If you are getting a bunch of information about the authors and articles on your website instead of the above error message? Then read on to disable the WordPress REST API.
Here’s how to disable the REST API for unauthorized users
Follow the steps below to make the WordPress REST API inaccessible to unauthorized users.
Note: You should not disable the REST API completely; in fact, this may break the functionality of the WordPress, as some functionality depends on an active API. However, you can use a filter to require that the API can only be used by authorized users, which effectively prevents anonymous external access.
- Open File Management
- Open the following location: httpdocs / wp-content / themes / theme name / functions.php
- Add the code below at the bottom of this file:
- Save the changes and then revisit the URL in an incognito window
/**
* Disable JSON API for unauthenticated users
*/
add_filter( 'rest_authentication_errors', function( $result ) {
// If a previous authentication check was applied,
// pass that result along without modification.
if ( true === $result || is_wp_error( $result ) ) {
return $result;
}
// No authentication has been performed yet.
// Return an error if user is not logged in.
if ( ! is_user_logged_in() ) {
return new WP_Error(
'rest_not_logged_in',
__( 'You are not currently logged in.' ),
array( 'status' => 401 )
);
}
// Our custom authentication check should have no effect
// on logged-in requests
return $result;
});