有没有办法可以限制对WP REST API的url调用的访问?我正在使用WP REST API来创建可以通过URL访问的AJAX提要。它们的格式如下:http://example.com/wp-json/posts?type=post&filter[posts_per_page]=10
问题是任何人都可以在我的网址末尾添加/wp-json/posts?type=post&filter[posts_per_page]=10
并检索此信息的Feed。当用户没有登录到WordPress时,我希望关闭此功能:
if ( !is_user_logged_in()) {
// Turn off REST API feed
}
或者,我想添加一些需要添加的身份验证来屏蔽api。
我在网上找到了这样的东西,但我没有运气好运。我将它添加到自定义插件中。不幸的是,我还是可以在未登录时访问Feed。
add_action( 'init', function() {
global $wp_post_types;
$wp_post_types['post']->show_in_rest = is_user_logged_in();
}, 20 );
我担心在激活API和在前端发出HTTP请求之间无法建立连接。我在想这个错吗?有人遇到过这个问题吗?
谢谢!
答案 0 :(得分:2)
这将删除未登录用户的所有WordPress和Woocommerce REST API端点:
function myplugin_removes_api_endpoints_for_not_logged_in() {
if ( ! is_user_logged_in() ) {
// Removes WordpPress endpoints:
remove_action( 'rest_api_init', 'create_initial_rest_routes', 99 );
// Removes Woocommerce endpoints
if ( function_exists('WC') )
remove_action( 'rest_api_init', array( WC()->api, 'register_rest_routes' ), 10 );
}
} add_action('init', 'myplugin_removes_api_endpoints_for_not_logged_in');
答案 1 :(得分:2)
Wordpress的问题和祝福是它提供了太多的灵活性,尤其是当平台提供了一种干净的方法时:Require Authentication for all requests
您可以通过添加一个对所有REST API请求进行身份验证 is_user_logged_in检查rest_authentication_errors过滤器。
注意:传入的回调参数可以为null,WP_Error, 或布尔值。参数的类型指示状态 身份验证:
- null:尚未执行身份验证检查,并且挂钩回调可以应用自定义身份验证逻辑。
- 布尔值:指示已执行先前的身份验证方法检查。布尔值true表示请求已成功
已验证,并且布尔值false表示验证失败。- WP_Error:遇到某种错误。
add_filter( 'rest_authentication_errors', function( $result ) {
// If a previous authentication check was applied,
// pass that result along without modification.
if ( true === $result || is_wp_error( $result ) ) {
return $result;
}
// No authentication has been performed yet.
// Return an error if user is not logged in.
if ( ! is_user_logged_in() ) {
return new WP_Error(
'rest_not_logged_in',
__( 'You are not currently logged in.' ),
array( 'status' => 401 )
);
}
// Our custom authentication check should have no effect
// on logged-in requests
return $result;
});
为了公平起见,这被隐藏在常见问题中。
编辑:排除jwt-auth
global $wp;
// No authentication has been performed yet.
// Return an error if user is not logged in and not trying to login.
if ( ! is_user_logged_in() && $wp->request !== 'wp-json/jwt-auth/v1/token' ) {
return new WP_Error(
'rest_not_logged_in',
__( 'You are not currently logged in.' ),
array( 'status' => 401 )
);
}
答案 2 :(得分:1)
这将阻止未登录的任何人使用整个REST API:
function no_valid_user_no_rest($user) {
if (!$user) {
add_filter('rest_enabled', '__return_false');
add_filter('rest_jsonp_enabled', '__return_false');
}
return $user;
}
add_filter('determine_current_user', 'no_valid_user_no_rest', 50);
标准警告,这只是关闭REST,没有别的。确保它具有足够的优先级来跟随其他determine_current_user
过滤器。没有在多站点上测试。
如果您想按网址或其他因素进行过滤,也可以向条件添加其他测试。