Prevent Non-Authenticated Access to WordPress REST API

I only recently became aware of the shenanigans from February with hackers attacking vulnerabilities in the WordPress Json REST API to deface sites. I wasn’t affected by this; and in actuality I hadn’t taken notice of the Api at all since I haven’t done anything yet that needs it.

Now I have taken notice and IMO there is a fundamental issue with it as it allows non-authenticated access to quite a lot of blog data in a way that is easy to probe very quickly with automated hacking tools1. ┬áNow this is kinda- not a big deal as the accessible data is supposedly public anyway, but after having a quick poke around the api end points I found a glaring security hole that I really don’t want to expose.

Navigating to the “wp-json/wp/v2/users” endpoint lists users that also authored pages, not just the users that have visible published posts. That includes my admin user that created the “About” and “Contact” pages and I really don’t want to expose any clues about the site administrator2.

So, I’m not happy at all having the api exposed, but fortunately the fix is very easy and straight out of the documentation. Adding the following code3 to the functions.php or a site-specific plugin restricts all api access to authenticated users:

add_filter( 'rest_authentication_errors', function( $result ) {
    if ( ! empty( $result ) ) {
        return $result;
    if ( ! is_user_logged_in() ) {
        return new WP_Error( 'rest_not_logged_in', 'You are not currently logged in.', 
        array( 'status' => 401 ) );
    return $result;

This works fine and keeps the api function intact, unlike other solutions that block the “users” endpoint completely4.

Another interesting thing I found is that requesting a list of categories in the api using “wp-json/wp/v2/categories” lists all categories, not just ones used in published posts – thereby revealing non-publicly available data – FAIL! Who knows what other holes are there in the api5???

Anyone else got misgivings about the potential security of the WordPress REST API?

[PS: For people not comfortable with coding there is a plugin that I believe uses the same approach as I do: Disable REST API by Dave McHale]



  1. Look how quickly the Feb hack blew up – scary.
  2. I could change the page author to my public persona too and have a completely separate login just for writing posts in-case I forget to change the publishing user, but what a ball-ache for a single-person blog…
  3. This needs PHP 5.3 or later, but FFS why is anyone running anything under 5.6 on a public site anyway?
  4. Although I’m sure it would be an easy elaboration to restrict this endpoint to logged-in users only.
  5. The api lists all uploaded media too via “wp-json/wp/v2/media”, in published posts or not – more FAIL!