Blog

How To Turn Off Public Access To The WordPress REST API

| Published by Callan Milne on August 10, 2020 12:30 pm
How To Turn Off Public Access To The WordPress REST API

Along with the new Gutenberg editor introduced in WordPress 5.0, there is a new REST Web API which exposes WordPress data to the public.

For example, you can now get a list of usernames for a WordPress website by visiting the Users list API Endpoint (/wp-json/wp/v2/users). E.g. https://example.com/wp-json/wp/v2/users.

While the REST Web API is required for Gutenberg to work properly, it is not required for your website to work properly–unless you’re using a plugin or theme, which uses the REST API for anything–which I would recommend against.

You can disable the REST API for non-admins very easily using the rest_api_init hook.

Add the following lines to your theme’s functions.php file to disable the REST API for users who are not logged in; and for logged in users who are not Editors, Administrators, or Authors.

add_filter( 'rest_api_init', 'rest_api_admins_only', 10 );
function rest_api_admins_only ( $wp_rest_server ) {
  if ( ! is_user_logged_in() ) {
    return rest_api_admins_only_error();
  }

  $user = wp_get_current_user();
  $allowed_roles = array(
    'editor',
    'administrator',
    'author',
  );

  if ( ! array_intersect( $allowed_roles, $user->roles ) ) {
    return rest_api_admins_only_error();
  }
}

function rest_api_admins_only_error () {
  wp_die(
    'Unauthorized!  You are not permitted to access this end point.',
    'Unauthorized Access',
    403
  );
}

For more information about the new WordPress REST API, check out the WordPress REST API Handbook.