Hiding WordPress REST API v2 endpoints from public viewing

I would like to start using the WordPress REST API v2 to query information from my site. I’ve noticed that when I visit an endpoint URL directly, I can see all of the data publicly. I’ve also seen that a lot of tutorials mention the use of test or local servers rather than live sites.

My questions are:

  • Is this meant to be used on sites in production?
  • Is there a security
    risk to allowing endpoints to be viewed by anyone, such as
    /wp-json/wp/v2/users/ which shows all users registered to the site?
  • Is it possible to allow only authorized users to access an endpoint?

I want to make sure that I am following best practices regarding security, so any tips would be helpful. The api docs mention authentication, but I’m not sure how to prevent the URL from being accessed directly. How do others usually set up this data to be accessed by external applications without exposing too much information?

5

Is this meant to be used on sites in production?

Yes. Many sites have been already using it.

Is there a security risk to allowing endpoints to be viewed by anyone, such as /wp-json/wp/v2/users/ which shows all users registered to the site?

No. Server responses have nothing to do with security, nothing you can do against a blank screen or read only response.

However, If your sites allow weak passwords, there’re some problems. But it’s your site’s policy, REST API knows nothing about that.

Is it possible to allow only authorized users to access an endpoint?

Yes. You can do it by using permission callback.

For example:

if ( 'edit' === $request['context'] && ! current_user_can( 'list_users' ) ) {
    return new WP_Error( 'rest_forbidden_context', __( 'Sorry, you cannot view this resource with edit context.' ), array( 'status' => rest_authorization_required_code() ) );
}

How do others usually set up this data to be accessed by external applications without exposing too much information?

This question is hard to answer because we don’t know what/when is too much information. But we can strictly follow API references and security cheatsheets to avoid unwanted situation.

Leave a Comment