rest api – Accessing an auth protected custom WP API enpoint from remote origin

Question

I’m creating a Chrome browser extension that connects to a WordPress through its custom REST API endpoints. Retrieving data types that don’t require an authorized user to be logged in works fine, as expected. But endpoints that do require the user to be logged in don’t. See the example below:

// backend code, in my wordpress plugin
add_action('rest_api_init', function() {
    //...
    register_rest_route( 'ept/v1', 'user/me', array(
        'methods' => 'GET',
        'callback' => 'get_curr_user',
        'permission_callback' => 'is_user_logged_in',
    ) );
    //...
}

function get_curr_user( $slug ) {
    $user = wp_get_current_user();
    return $user;
}

I guessed that in order to access that endpoint I must provide a wp-nonce in the query params or in the header of the HTTP request, since otherwise you’ll get a 401 status – “rest_forbidden” exception. So, also for testing purposes only, I created this page in the wordpress website that generates a nonce for the logged in user and adds it as a query param to enpoint’s API link:

<?php
/*
 * Template Name: API test
 * */

$nonce = wp_create_nonce( 'wp_rest' );
?>

<a href="https://my-domain-here.com/wp-json/ept/v1/user/me?_wpnonce=<?php echo $nonce; ?>">endpoint</a>

This links works, no exceptions thrown in the HTTP response. So I thought maybe I would be able to generate a new nonce in that page and use it in a request made from the Chrome extension. My only intention with that was to discover whether nonces could work in my chrome extension. But it didn’t work, instead I got a 403 status – “rest_cookie_invalid_nonce” exception. Here’s what the request looked like:

// Chrome extension code
const url = `https://my-domain-here.com/wp-json/ept/v1/user/me?_wpnonce=${wpNonce}`;
    const request = {
        method: "GET",
        headers: {
            'Content-Type': 'application/json',
        }, 
    }

    await fetch(url, request)
        .then(response => response.json())
        .then((data) => {
            // some code...
        })

I can only guess wp-nonce isn’t the way to do it when making call from remote origins. So what’s the way to it correctly and, most importantly, safely? I have read about application passwords, but I don’t know if they will be of help in my situation. I also wouldn’t know how to implement application passwords when I already multiple active users.

To summarize, is there a practical way to call a WP custom REST API endpoint which requires auth from a Chrome extension or any remote origin?

0
Vitor Rodrigues 5 months 2023-10-17T13:42:50-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse