Disabling WordPress public REST API

I've recently found that the public WP REST API endpoints within WordPress can provide information which can be used in 'hacking' attempts.

One such endpoint is '/wp-json/wp/v2/users' (e.g. https://yourdomain.com/wp-json/wp/v2/users), this will display Admin usernames to any unauthenticated user.

There are a couple of way to mitigate this risk, install the Disable REST API or add this function to your theme's 'functions.php' file:

Sites running WordPress 4.7 or greater

/**
 * Disable the REST API for non-logged in users. E.g. https://yourdomain.com/wp-json/wp/v2/users/. (WordPress 4.7 and greater)
 * Last modified: September 2017
 * @author Ryan Fitton
 * @copyright Copyright (c) 2017, Ryan Fitton
*/
function disable_rest_api_non_loggged_in_user( $access ) {
	if( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) {
		return new WP_Error( 'rest_cannot_access', __( 'REST API access has been disabled for non-authenticated users.', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
	}
	return $access;
}
add_filter( 'rest_authentication_errors', 'disable_rest_api_non_loggged_in_user' );

Sites older than WordPress 4.7

/**
 * Disable the REST API for non-logged in users. (Older than WordPress 4.7)
 * Last modified: September 2017
 * @author Ryan Fitton
 * @copyright Copyright (c) 2017, Ryan Fitton
*/
// Filters for WP-API version 1.x
add_filter( 'json_enabled', '__return_false' );
add_filter( 'json_jsonp_enabled', '__return_false' );

// Filters for WP-API version 2.x
add_filter( 'rest_enabled', '__return_false' );
add_filter( 'rest_jsonp_enabled', '__return_false' );

Discuss on X (Twitter)