WordPress API Permission Callback – Check if user is logged in

Viewed 9356

I have a question about permission callbacks when working with the WP Rest API. I have registered a couple of endpoints using register_rest_route and simply want to secure them so that you can’t access the content if you’re not logged in.

add_action('rest_api_init', 'register_custom_endpoints');

function register_custom_endpoints(){
    register_rest_route($base, $endpoint, [
        'methods' => 'POST',
        'callback' => function($request){
            // Return JSON data
        },
        'permission_callback' => function($request){
            // This always returns false
            return is_user_logged_in();
        },
    ]);
}

I think my logic here is correct but is_user_logged_in() always returns false, meaning I’ll never get the data even if I’m actually logged in. All I get is a 404 response:

{code: "rest_user_invalid_id", message: "Invalid user ID.", data: {status: 404}}

I’ve been scouring the web for answers and what I’ve found is that I need to send a nonce with the request. I’ve tried sending it both as body data and as a header. If I send it in the body, I can’t verify it as it always returns false. And if I send it as a header, I get the same 404 response as stated above.

What am I missing here, and what am I doing wrong?

2 Answers

I recently encountered the same issue and it turns out that you need to create a nonce and pass it with your request headers.

You create the appropriate nonce with the following php code.

$nonce = wp_create_nonce( 'wp_rest' );

Then you pass that nonce with the HTTP request via the header X-WP-Nonce.

Assuming your client is on the same domain (ergo has WordPress's auth cookies set) your session should be accessible via the REST API so functions like current_user_can and is_user_logged_in work as they would outside the REST API.

Related