Search code examples
wordpressrestwordpress-rest-api

WP REST API Set Permission for Existing Endpoints


I have a custom post type, card, that I'm exposing through the 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' );

It seems like by default, the endpoints are public. How do I set the authentication requirements for the endpoint, so that GET /cards/ requires either an auth cookie or header?

In the API handbook is shows how to write a custom endpoint, but ideally is there a filter or hook I can use to extend the autogenerated endpoints?

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' );
        }
    ) );
} );

Solution

  • You can use the rest_pre_dispatchfilter to check the URL and revoke access to that endpoint for not logged in users:

    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 ) );
        }
    } );
    

    This is not the best solution because it will run the query and will filter the result, but I'm using this until discover a way to block the API access before the query is executed.