WP Statistics插件在开启缓存功能后无法统计访问量

WP Statistics插件在开启缓存功能后无法统计访问量。

跟踪发现统计访问量使用的url返回401错误,如下:

https://www.mobibrw.com/wp-json/wpstatistics/v1/hit?_=1603432478&_wpnonce=1b5c35aa31&wp_statistics_hit_rest=yes&ua=Mozilla/5.0%20(Macintosh;%20Intel%20Mac%20OS%20X%2010_15_7)%20AppleWebKit/605.1.15%20(KHTML,%20like%20Gecko)%20Version/14.0%20Safari/605.1.15&url=https://www.mobibrw.com/2020/27156&referred=

Failed to load resource: the server responded with a status of 401 (Unauthorized)

比较奇怪的是,如果此时用户登陆,那么反倒不返回任何错误了。

查找了很长时间,才发现原因是自定义的这段防护代码导致的

<?php
  /*.禁用REST API,Workpress 4.7.1版本等版本上出现大量的攻击异常都是这个API导致的
,安全风险非常大,又没有什么鸟用,直接禁用,脑残的是从4.7版本开始,没办法彻底禁用
,导致只能使用如下方法才能基本限制用户的访问*/
  add_filter('rest_authentication_errors','disable_rest_api');
  function disable_rest_api() {
    if(!is_user_logged_in()) {
      return new WP_Error('Error!', __('Unauthorized access is denied!', 'rest-api-error'), array('status' => rest_authorization_required_code()));
    }
  }
?>

修改方式为,许可`wp-json/wpstatistics/v1/hit`的访问,如下

<?php
  /*.禁用REST API,Workpress 4.7.1版本等版本上出现大量的攻击异常都是这个API导致的
,安全风险非常大,又没有什么鸟用,直接禁用,脑残的是从4.7版本开始,没办法彻底禁用
,导致只能使用如下方法才能基本限制用户的访问
,但是部分需要REST API的插件需要增加特例许可,否则功能不可用,
,比如 WP Statistics 插件 需要访问 wp-json/wpstatistics/v1/hit */
  add_filter('rest_authentication_errors','disable_rest_api');
  function disable_rest_api() {
    if(!is_user_logged_in() && !strpos($_SERVER['REQUEST_URI'], "wp-json/wpstatistics/v1/hit?") && !strpos($_SERVER['REQUEST_URI'], "wp-json/wp-statistics/v2/hit?")) {
      return new WP_Error('Error!', __('Unauthorized access is denied!', 'rest-api-error'), array('status' => rest_authorization_required_code()));
    }
  }
?>

参考连接


Filtering `rest_authentication_errors` to `true` to get jwt-auth work

发布者

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注