向公众隐藏WordPress REST API v2端点

时间:2016-06-02 作者:Morgan

我想开始使用WordPress REST API v2 从我的网站查询信息。我注意到,当我直接访问端点URL时,我可以公开查看所有数据。我还看到很多教程提到使用测试或本地服务器,而不是实时站点。

我的问题是:

这是否用于生产现场/wp-json/wp/v2/users/ 显示所有注册到该站点的用户我想确保我遵循了有关安全性的最佳实践,所以任何提示都会很有帮助。这个api docs 提到身份验证,但我不确定如何防止直接访问URL。其他人通常如何设置这些数据以供外部应用程序访问,而不暴露太多信息?

5 个回复
最合适的回答,由SO网友:dan9vu 整理而成

这是否用于生产现场?

Many sites have been already using it.

允许任何人查看端点是否存在安全风险,例如/wp-json/wp/v2/users/显示所有注册到该站点的用户?

否。服务器响应与安全无关,您无法对空白屏幕或只读响应执行任何操作。

但是,如果您的站点允许弱密码,则some problems. 但这是您站点的策略,REST API对此一无所知。

是否可以只允许授权用户访问端点?

对您可以使用permission callback.

例如:

if ( \'edit\' === $request[\'context\'] && ! current_user_can( \'list_users\' ) ) {
    return new WP_Error( \'rest_forbidden_context\', __( \'Sorry, you cannot view this resource with edit context.\' ), array( \'status\' => rest_authorization_required_code() ) );
}
其他人通常如何设置这些数据以供外部应用程序访问,而不暴露太多信息?

这个问题很难回答,因为我们不知道什么时候有太多的信息。但我们可以严格遵守API referencessecurity cheatsheets 避免不必要的情况。

SO网友:Dalton Rooney

是否可以只允许授权用户访问端点?

可以向API端点添加自定义权限回调,该回调需要身份验证才能查看内容。未经授权的用户将收到错误响应"code": "rest_forbidden"

最简单的方法是扩展WP\\u REST\\u Posts\\u控制器。下面是一个非常简单的例子:

class My_Private_Posts_Controller extends WP_REST_Posts_Controller {

   /**
   * The namespace.
   *
   * @var string
   */
   protected $namespace;

   /**
   * The post type for the current object.
   *
   * @var string
   */
   protected $post_type;

   /**
   * Rest base for the current object.
   *
   * @var string
   */
   protected $rest_base;

  /**
   * Register the routes for the objects of the controller.
   * Nearly the same as WP_REST_Posts_Controller::register_routes(), but with a 
   * custom permission callback.
   */
  public function register_routes() {
    register_rest_route( $this->namespace, \'/\' . $this->rest_base, array(
        array(
            \'methods\'             => WP_REST_Server::READABLE,
            \'callback\'            => array( $this, \'get_items\' ),
            \'permission_callback\' => array( $this, \'get_items_permissions_check\' ),
            \'args\'                => $this->get_collection_params(),
            \'show_in_index\'       => true,
        ),
        array(
            \'methods\'             => WP_REST_Server::CREATABLE,
            \'callback\'            => array( $this, \'create_item\' ),
            \'permission_callback\' => array( $this, \'create_item_permissions_check\' ),
            \'args\'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::CREATABLE ),
            \'show_in_index\'       => true,
        ),
        \'schema\' => array( $this, \'get_public_item_schema\' ),
    ) );

    register_rest_route( $this->namespace, \'/\' . $this->rest_base . \'/(?P<id>[\\d]+)\', array(
        array(
            \'methods\'             => WP_REST_Server::READABLE,
            \'callback\'            => array( $this, \'get_item\' ),
            \'permission_callback\' => array( $this, \'get_item_permissions_check\' ),
            \'args\'                => array(
                \'context\' => $this->get_context_param( array( \'default\' => \'view\' ) ),
            ),
            \'show_in_index\'       => true,
        ),
        array(
            \'methods\'             => WP_REST_Server::EDITABLE,
            \'callback\'            => array( $this, \'update_item\' ),
            \'permission_callback\' => array( $this, \'update_item_permissions_check\' ),
            \'args\'                => $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE ),
            \'show_in_index\'       => true,
        ),
        array(
            \'methods\'             => WP_REST_Server::DELETABLE,
            \'callback\'            => array( $this, \'delete_item\' ),
            \'permission_callback\' => array( $this, \'delete_item_permissions_check\' ),
            \'args\'                => array(
                \'force\' => array(
                    \'default\'     => true,
                    \'description\' => __( \'Whether to bypass trash and force deletion.\' ),
                ),
            ),
            \'show_in_index\'       => false,
        ),
        \'schema\' => array( $this, \'get_public_item_schema\' ),
    ) );     
  }

  /**
   * Check if a given request has access to get items
   *
   * @param WP_REST_Request $request Full data about the request.
   * @return WP_Error|bool
   */
  public function get_items_permissions_check( $request ) {
    return current_user_can( \'edit_posts\' );
  }

}
您会注意到权限回调function get_items_permissions_check 使用current_user_can 确定是否允许访问。根据您使用API的方式,您可能需要了解有关客户端身份验证的更多信息。

然后,您可以通过在中添加以下参数,向REST API支持注册自定义post类型register_post_type

  /**
   * Register a book post type, with REST API support
   *
   * Based on example at: http://codex.wordpress.org/Function_Reference/register_post_type
   */
  add_action( \'init\', \'my_book_cpt\' );
  function my_book_cpt() {
    $labels = array(
        \'name\'               => _x( \'Books\', \'post type general name\', \'your-plugin-textdomain\' ),
        \'singular_name\'      => _x( \'Book\', \'post type singular name\', \'your-plugin-textdomain\' ),
        \'menu_name\'          => _x( \'Books\', \'admin menu\', \'your-plugin-textdomain\' ),
        \'name_admin_bar\'     => _x( \'Book\', \'add new on admin bar\', \'your-plugin-textdomain\' ),
        \'add_new\'            => _x( \'Add New\', \'book\', \'your-plugin-textdomain\' ),
        \'add_new_item\'       => __( \'Add New Book\', \'your-plugin-textdomain\' ),
        \'new_item\'           => __( \'New Book\', \'your-plugin-textdomain\' ),
        \'edit_item\'          => __( \'Edit Book\', \'your-plugin-textdomain\' ),
        \'view_item\'          => __( \'View Book\', \'your-plugin-textdomain\' ),
        \'all_items\'          => __( \'All Books\', \'your-plugin-textdomain\' ),
        \'search_items\'       => __( \'Search Books\', \'your-plugin-textdomain\' ),
        \'parent_item_colon\'  => __( \'Parent Books:\', \'your-plugin-textdomain\' ),
        \'not_found\'          => __( \'No books found.\', \'your-plugin-textdomain\' ),
        \'not_found_in_trash\' => __( \'No books found in Trash.\', \'your-plugin-textdomain\' )
    );

    $args = array(
        \'labels\'             => $labels,
        \'description\'        => __( \'Description.\', \'your-plugin-textdomain\' ),
        \'public\'             => true,
        \'publicly_queryable\' => true,
        \'show_ui\'            => true,
        \'show_in_menu\'       => true,
        \'query_var\'          => true,
        \'rewrite\'            => array( \'slug\' => \'book\' ),
        \'capability_type\'    => \'post\',
        \'has_archive\'        => true,
        \'hierarchical\'       => false,
        \'menu_position\'      => null,
        \'show_in_rest\'       => true,
        \'rest_base\'          => \'books-api\',
        \'rest_controller_class\' => \'My_Private_Posts_Controller\',
        \'supports\'           => array( \'title\', \'editor\', \'author\', \'thumbnail\', \'excerpt\', \'comments\' )
    );

    register_post_type( \'book\', $args );
}
你会看到的rest_controller_class 使用My_Private_Posts_Controller 而不是默认控制器。

我发现很难找到在documentation. 我确实觉得这个很棒explanation of extending the default controller, 这里有一个very thorough guide to adding endpoints.

SO网友:squarecandy

以下是我用来阻止所有未登录用户使用REST API的方法:

add_filter( \'rest_api_init\', \'rest_only_for_authorized_users\', 99 );
function rest_only_for_authorized_users($wp_rest_server){
    if ( !is_user_logged_in() ) {
        wp_die(\'sorry you are not allowed to access this data\',\'cheatin eh?\',403);
    }
}

SO网友:Josep Marxuach

最好的选择是禁用V5新编辑器,然后禁用API json,如下所述。

https://codber.com/2020/05/01/how-to-disable-wordpress-rest-api-to-not-logged-in-user-without-a-plugin/

SO网友:dipen patel
add_filter( \'rest_api_init\', \'rest_only_for_authorized_users\', 99 );
function rest_only_for_authorized_users($wp_rest_server)
{
if( !is_user_logged_in() ) 

    wp_die(\'sorry you are not allowed to access this data\',\'Require Authentication\',403);
} } 
function json_authenticate_handler( $user ) {

global $wp_json_basic_auth_error;

$wp_json_basic_auth_error = null;

// Don\'t authenticate twice
if ( ! empty( $user ) ) {
    return $user;
}

if ( !isset( $_SERVER[\'PHP_AUTH_USER\'] ) ) {
    return $user;
}

$username = $_SERVER[\'PHP_AUTH_USER\'];
$password = $_SERVER[\'PHP_AUTH_PW\'];


remove_filter( \'determine_current_user\', \'json_authenticate_handler\', 20 );

$user = wp_authenticate( $username, $password );

add_filter( \'determine_current_user\', \'json_authenticate_handler\', 20 );

if ( is_wp_error( $user ) ) {
    $wp_json_basic_auth_error = $user;
    return null;
}

$wp_json_basic_auth_error = true;

return $user->ID;}add_filter( \'determine_current_user\', \'json_authenticate_handler\', 20 );

相关推荐

Media Library http to https

我的网站当前显示混合内容,因为媒体库中的图像位于http.我使用了一些插件来更新URL并搜索和替换所有http 参考https.我已经更新了site url and site address via mysql.但是,媒体库的使用仍然不一致http://.媒体库还需要在哪里更新才能更改为https?