在 JavaScript AJAX 调用中保护 REST API 令牌

Secure REST API token in a JavaScript AJAX call

我需要将数据从第 3 方 REST API 拉入 WordPress 页面。这是一个搜索应用程序,所以我想尽可能避免通过 AJAX 刷新页面和加载结果。

API设置如下:

在前端应用程序中保护登录凭据和令牌的最佳做法是什么?

即使在服务器上使用 wp_remote_post 处理身份验证,我如何将令牌值传递给 JavaScript 而不在浏览器中公开它?

出于您在问题中提到的确切原因,最好在服务器端构建一个包装器。您不想在前端公开您的不记名令牌!

add_action('rest_api_init', function () {
  register_rest_route('user5050800/v1', '/search', [
    'methods' => 'GET',
    'callback' => 'search_wrapper',
  ]);
});

function search_wrapper(WP_REST_Request $request) {
  try {
    // make the req
    wp_remote_post($request->get_query_params()); // or something
  } catch (\WP_Error $e) {
    // figure out if it's a 403, or if you might need to make an additional req to get a new token and try again
  }
}