1

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.

2
  • 2
    Is there a particular endpoint you want to require authentication? Note that this might cause problems, for example a brute force answer would break OEmbeds, and might even break your oAuth, amongst other things. If we knew more about the context for why you would need to restrict things it would be helpful. In the meantime, you can still make an authenticated request to an endpoint that doesn't require authentication
    – Tom J Nowell
    Commented Mar 9, 2020 at 22:29
  • I get it, you're actually right. Since WordPress is a very complex structure, we cannot close it all at once. So suppose then, if we just do such an operation on / posts / endpoint?
    – P.Works
    Commented Mar 10, 2020 at 10:26

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.