WP REST API设置现有端点的权限

时间:2017-05-01 21:51:11

标签: wordpress rest wordpress-rest-api

我有一个自定义帖子类型card,我通过WP REST API公开。

function register_card_post_type() {
    $labels = array(
        "name" => __( 'Cards', '' ),
        "singular_name" => __( 'Card', '' ),
    );

    $args = array(
        "label" => __( 'Cards', '' ),
        "labels" => $labels,
        "description" => "",
        "public" => true,
        "publicly_queryable" => true,
        "show_ui" => true,
        "show_in_rest" => true,   // ADD TO REST API
        "rest_base" => "cards",   // ADD TO REST API
        "has_archive" => false,
        "show_in_menu" => true,
        "exclude_from_search" => false,
        "capability_type" => "post",
        "map_meta_cap" => true,
        "hierarchical" => false,
        "rewrite" => array( "slug" => "card", "with_front" => true ),
        "query_var" => true,
        "menu_position" => 5,
        "supports" => array( "title" ),
    );

    register_post_type( "card", $args );
}

add_action( 'init', 'register_card_post_type' );

默认情况下,端点似乎是公共的。如何设置端点的身份验证要求,以便GET /cards/需要身份验证cookie或标头?

在API手册中展示了如何编写自定义端点,但理想情况下是否有可用于扩展自动生成端点的过滤器或钩子?

add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
        'methods' => 'GET',
        'callback' => 'my_awesome_func',
        'args' => array(
            'id' => array(
                'validate_callback' => 'is_numeric'
            ),
        ),
        'permission_callback' => function () {
            return current_user_can( 'edit_others_posts' );
        }
    ) );
} );

1 个答案:

答案 0 :(得分:4)

您可以使用rest_pre_dispatch过滤器检查URL并撤消对未登录用户的该终端的访问权限:

add_filter( 'rest_pre_dispatch', function() {
     $url = strtok($_SERVER["REQUEST_URI"],'?');
     if ( !is_user_logged_in() &&  
          !in_array($url, array ( //using "in_array" because you can add mmultiple endpoints here
                        "/wp-json/cards",
                        ))){         
      return new WP_Error( 'not-logged-in', 'API Requests to '.$url.' are only supported for authenticated requests', array( 'status' => 401 ) );
    }
} );

这不是最佳解决方案,因为它将运行查询并将过滤结果,但我一直在使用它,直到在执行查询之前发现阻止API访问的方法。