让代码更简单

WordPress限制或禁用REST API

REST API是WordPress提供的一套api,为什么要禁用它?当然是它泄露数据啦!在网站 URL 末尾添加
/wp-json/wp/v2/users,就可以列出所有注册用户!甚至有些爬虫都不爬前端,直接使用REST API获取你的网站内容,还能避免各种样式广告等造成的解析问题。

写到一半突然感觉有点熟悉,于是搜索了一下,发现6年前狗哥就发布过相关文章,不过6年过去了,谁知道有没有变化呢,本文就当是补充更新了,WordPress控制REST API访问权限代码

直接禁用,只需要在functions.php文件中添加如下代码即可。

复制
add_filter( 'rest_authentication_errors', 'dmd_turn_off_rest_api' );

function dmd_turn_off_rest_api( $errors ) {

	// if there is already an error, just return it
	if( is_wp_error( $errors ) ) {
		return $errors;
	}

	// return WP_Error object
	return new WP_Error( 'no_rest_api_sorry', 'REST API not allowed', array( 'status' => 401 ) );

	return $errors;
	
}

如果你使用了Gutenberg编辑器,你会发现编辑文章时会报错,因为Gutenberg编辑器使用的就是REST API实现的编辑文章功能,所以禁用它并不是最佳方案。

你可以为REST API增加权限检查,只允许登录用户或者管理员访问,使用如下代码

复制
add_filter( 'rest_authentication_errors', 'dmd_turn_off_rest_api_not_logged_in' );

function dmd_turn_off_rest_api_not_logged_in( $errors ) {

	// if there is already an error, just return it
	if( is_wp_error( $errors ) ) {
		return $errors;
	}
	
	if( ! is_user_logged_in() ) {
		// return WP_Error object if user is not logged in
		return new WP_Error( 'no_rest_api_sorry', 'REST API not allowed', array( 'status' => 401 ) );
	}
	
	return $errors;
	
}

管理员可用

复制
add_filter( 'rest_authentication_errors', 'dmd_turn_off_rest_api_not_logged_in' );

function dmd_turn_off_rest_api_not_logged_in( $errors ) {

	// if there is already an error, just return it
	if( is_wp_error( $errors ) ) {
		return $errors;
	}
	
	if( ! current_user_can( 'administrator' ) ) {
	// disable REST API for everyone except administrators
	return new WP_Error( 'no_rest_api_sorry', 'REST API not allowed', array( 'status' => 401 ) );
      }
	
	return $errors;
	
}

使用IP白名单限制

复制
add_filter( 'rest_authentication_errors', 'dmd_allow_rest_api_for_ip' );

function dmd_allow_rest_api_for_ip( $errors ) {

	// if there is already an error, just return it
	if( is_wp_error( $errors ) ) {
		return $errors;
	}
	
	$whitelist = array( 
		'37.33.184.198',
		'62.74.24.234',
		// etc
	);
	
	if( ! in_array( $_SERVER[ 'REMOTE_ADDR' ], $whitelist ) ){
		// return WP_Error object if user is not logged in
		return new WP_Error( 'no_rest_api_sorry', 'REST API not allowed', array( 'status' => 401 ) );
	}
	
	return $errors;
	
}

以上方法被禁止访问,返回的是json数据,你也可以改成404页面,将返回的wp_error更换为如下代码即可。

复制
header( 'Content-Type: text/html; charset=UTF-8' );
status_header( 404 );
nocache_headers();
require( dirname( __FILE__ ) . '/404.php' );
die;

当然还有更好的办法,将REST API路径给修改了,这样既不会影响WordPress系统运行,也不会阻止任何用户使用,前提是知道URL。

复制
add_filter( 'rest_url_prefix', 'dmd_custom_rest_api_url' );

function dmd_custom_rest_api_url() {
	return 'api';
}

推荐使用最后一种方法,但如果你的网站是单机版,不需要用户,直接禁用最佳。

感觉很棒!可以赞赏支持我哟~

0 打赏

评论 (0)

登录后评论
QQ咨询 邮件咨询 狗哥推荐