使用内部WP_REST_REQUEST和REST_DO_REQUEST()进行身份验证

时间:2020-09-14 作者:Tom

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().

1 个回复
SO网友:Tom J Nowell

如何为rest\\u do\\u request()添加身份验证?

No. This solution to your problems will not work, and it will not save time or effort.

事实上,这将需要广泛而一致的努力和大量的时间。尽管这样做的全部目的是通过使用RESTAPI来避免处理未记录的PHP代码。

根本问题是rest_do_request 在与当前页面加载相同的请求中处理请求,因此它在相同的上下文中运行。

因此,为了实现您的目标,我们需要欺骗WordPress,使其认为您已登录,并且是有权使用该路径的其他人。然后,路由使用的每一个API都会继续执行此操作。

最重要的是,插件可以根据上下文加载不同的代码,因此您需要更改它们的加载方式,但您不知道是否需要这样做,因为短代码的处理要晚得多。

因此,您需要对WordPress的内部状态进行重大调整,以及对插件进行大量调整,可能会导致插件分叉。

唯一实用的方法是使用HTTP API发出REST API请求,但这将带来巨大的性能成本。

不管怎样,这种方法都没有好处