We may want to restrict access to the WordPress REST API.

For example, by default, WordPress has a file that contains information about the authors of the site that is publicly available at example.com/wp-json/wp/v2/users.

It may be a good idea to make this file available only to authorized users.

The following function allows only logged-in users, who have post editing permissions (e.g. author, editor, administrator), to access the REST API.

/**
 * Restricts access to WordPress REST API.
 *
 * @link https://notesontech.com/restricting-access-to-wordpress-rest-api/
 */
add_filter(
	'rest_authentication_errors',
	function( $result ) {

		if ( ! empty( $result ) ) {
			return $result;
		}

		if ( ! ( is_user_logged_in() && current_user_can( 'edit_posts' ) ) ) {

			return new WP_Error(
				'rest_cannot_access',
				'Only authorized users can access the REST API.',
				array( 'status' => 401 )
			);

		}

		return $result;
	}
);

This function can be added to the functions.php file of the theme or to another theme configuration file if one exists.