Out of the box, the REST API hands public content to anyone who asks. On a site where I wouldn’t want that, I’d reach for the rest_authentication_errors filter. It is the one place where WordPress asks whether a request is allowed in.
add_filter( 'rest_authentication_errors', function ( $result ) {
// Another method already answered: leave it alone.
if ( null !== $result ) {
return $result;
}
if ( ! is_user_logged_in() ) {
return new WP_Error(
'rest_not_logged_in',
'You must be logged in.',
array( 'status' => 401 )
);
}
return $result;
} );
The filter passes along a WP_Error, null or true. A WP_Error means authentication failed. null means the method wasn’t used. true means authentication succeeded. The docs say a callback should check for null before it looks at errors, because several authentication methods can be active on one site and each should only act when it’s the one being used. That is why the first lines of the example return early.
The error should follow the format the API uses internally, which means a status entry in the data. The filter exists since WordPress 4.4.0.
Caveats: this example follows the documented semantics but was not run against a live site. It also locks out everything, including public clients, so a plugin or a headless front end that reads posts anonymously will break. Test it on a staging copy first.
Further reading: rest_authentication_errors hook reference