【问题标题】:Secure REST API token in a JavaScript AJAX callJavaScript AJAX 调用中的安全 REST API 令牌
【发布时间】:2020-10-15 08:40:58
【问题描述】:

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

API 设置如下:

  • 需要用户/密码才能获取不记名令牌(POST 请求,单独的端点)
  • 对 API 的每个 GET 请求都需要不记名令牌
  • 令牌每 30 天过期一次

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

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

【问题讨论】:

    标签: ajax wordpress restful-authentication


    【解决方案1】:

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

    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
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2015-05-24
      • 2017-05-19
      • 1970-01-01
      • 2013-11-03
      • 2021-09-23
      • 2021-05-02
      相关资源
      最近更新 更多