【问题标题】:WordPress REST API - browser gives JSON response without authenticationWordPress REST API - 浏览器无需身份验证即可提供 JSON 响应
【发布时间】:2016-08-18 03:43:11
【问题描述】:

我正在使用 WP REST API 和 oAuth1.0 服务器插件进行身份验证。到目前为止,Postman 需要经过身份验证才能访问端点,但浏览器不需要身份验证。任何人都可以通过浏览器访问 API 响应。是否可以限制浏览器中的 API 访问?我不希望未经身份验证的人看到 API 的敏感数据。

附: oAuth1.0 服务器插件已激活,Postman 中的身份验证完美运行!

示例。当我在浏览器中输入 http://localhost:8080/api/v1/categories 时,我得到类别的 JSON 响应,当我在 Postman 中输入相同的端点时,我得到:

{
  "code": "json_oauth1_missing_parameter",
  "message": "Missing OAuth parameter oauth_token",
  "data": {
    "status": 401
  }
}

【问题讨论】:

    标签: php wordpress api rest oauth


    【解决方案1】:

    好的,经过一整天的搜索,我终于找到了两种可能的解决方案。两者都适合我(个人选择了第一个)。

    add_filter('rest_pre_dispatch', function($result){
        if (is_user_logged_in()) {
            return $result;
        } else {
            return new WP_Error('rest_requires_authentication', __('Authentication is required for this action.'), array('status' => 403));
        }
    });
    

    或者

    add_filter('rest_authentication_errors', function($result) {
        if (!empty($result)) {
            return $result;
        }
        if (!is_user_logged_in()) {
            return new WP_Error('restx_logged_out', 'Sorry, you must be logged in to make a request.', array('status' => 401));
        }
        return $result;
    });
    

    很遗憾 WP REST API 插件自己没有处理这个问题。

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 2018-09-27
      • 2013-01-05
      • 2011-04-28
      • 1970-01-01
      • 2020-05-20
      • 2017-03-04
      • 1970-01-01
      • 2018-08-14
      相关资源
      最近更新 更多