繁体   English   中英

WordPress REST API - 浏览器无需身份验证即可提供JSON响应

[英]WordPress REST API - browser gives JSON response without authentication

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

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

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

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插件本身并没有处理它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM