How can I add authentication for rest_do_request()
? I am trying to add Authentication for a WP_REST_Request
object using rest_do_request()
. This used within a shortcode that is going to be available for both logged in and non logged in users.
I\'m thinking that the best way would be to use Basic Authorization. In an example I\'ve setup, I\'ve added the following line commented with "Basic Authorization Attempt" which does not appear to have any effect.
If it\'s not possible to add authentication, is there another method such as running certain requests as another user or force rest_do_request() to run regardless of permission?
Here is an example of trying to use WP_REST_Request and rest_do_request() with Retrieving orders from WooCommerce:
$request = new WP_REST_Request(\'GET\', \'/wc/v3/orders\');
$request->set_headers([
\'Content-Type\' => \'application/json\',
\'Authorization\' => \'Basic \' .
base64_encode( \'ck_The_Consumer_Key:cs_The_Consumer_Secret\' ) // Basic Authorization Attempt
]);
$response = rest_do_request($request);
$decoded_response = $response->get_data();
return json_encode($decoded_response);
When I\'m logged into my admin account, and visit this page, I get the following output as expected:
[{"id":498,"parent_id":0,"number":"498","order_key":"wc_order_...
When I\'m not logged in and visit the page with the shortcode, the following is returned:
{"code":"woocommerce_rest_cannot_view","message":"Sorry, you cannot list resources.","data":{"status":401}}
In fact, removing the Authorization header from $request->set_headers()
has no effect on the output of either of the two examples, running under a logged in admin account and a non-logged in account.
Please note: While this example uses WooCommerce, this question is specific to WP_REST_Request and rest_do_request().