The WordPress REST API was introduced in the WordPress core at the end of 2016 with the release of WordPress 4.6. Like all the big changes that appear in the platform, the REST API generated controversy in some and indifference in others.
It’s even possible that you have no idea what it is, but if you have an updated version of WordPress (and you should) you are exposing many aspects of your website publicly through the REST API. Just append the fragment /wp-json/
to your domain name and visit this URL to see it with your own eyes.
Moreover, do the exercise of visiting the following web URLs and you may be surprised with what you’ll find:
mydomain.com/wp-json/wp/v2/users
mydomain.com/wp-json/wp/v2/posts
As a result of the first URL you will have a JSON with the data of the users of your web. Notice that user identifiers are included there, and this is something that people traditionally hide due to security issues and to prevent possible attacks.
The second URL shows us a list with the last posts. However, if you have protected content that only certain premium users of your website (in a membership site, for example) should have access to, it’s possible that you’ve been exposing this premium content through the REST API.
Let’s see how we can avoid compromised situations by being more aware of what we publicly expose through the WordPress REST API.
Show WordPress REST API Only to Registered Users
A solution that we can implement to hide the WordPress REST API is to prevent those users who are not registered on our website from accessing it.
To hide the REST API to unregistered users, we must add the following code in our WordPress. Remember that you can put it in the functions.php
file of your theme or just develop a plugin for it (a much better option).
}
if ( ! current_user_can( 'administrator' ) ) {
return new WP_Error( 'rest_not_admin', 'You are not an administrator.', array( 'status' => 401 ) );
}
return $result;
});
}
return $result;
});