WP REST API GET Requests require authentication

Is there a way to require authentication for WP REST API GET Requests?

The people I was researching always added a command if the is_user_logged_in(). But it closes these external queries altogether. My purpose is that someone who owns a token with oAuth can request a GET.

Topic oauth authentication rest-api Wordpress

Category Web


I've been working on a similar issue today. Here's what I've done:

add_filter('rest_dispatch_request', function($dispatch_result, $request, 
$route, $handler) {
    if (!is_user_logged_in()) {
        $dispatch_result = new WP_Error(
            'rest_not_logged_in',
            __( 'You are not currently logged in.' ),
            array( 'status' => 401 )
        );
    }

    return $dispatch_result;
}, 10, 4);

You may want to use the $handler to determine which requests you want to restrict.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.