¿Es posible permitir que solo los usuarios autorizados accedan a un punto final?
Es posible agregar una devolución de llamada de permiso personalizada a su punto final de API que requiere autenticación para ver el contenido. Los usuarios no autorizados recibirán una respuesta de error."code": "rest_forbidden"
La forma más sencilla de hacer esto es extender el WP_REST_Posts_Controller. Aquí hay un ejemplo muy simple de eso:
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' );
}
}
Notará que la devolución de llamada de permisos se function get_items_permissions_check
utiliza current_user_can
para determinar si se debe permitir el acceso. Dependiendo de cómo esté utilizando la API, es posible que deba aprender más sobre la autenticación del cliente.
A continuación, puede registrar su tipo de publicación personalizada con soporte de API REST agregando los siguientes argumentos en 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 );
}
Verá rest_controller_class
usos en My_Private_Posts_Controller
lugar del controlador predeterminado.
Me ha resultado difícil encontrar buenos ejemplos y explicaciones para usar la API REST fuera de la documentación . Encontré esta gran explicación de extender el controlador predeterminado , y aquí hay una guía muy completa para agregar puntos finales .