For those reading this post in 2021, adding to the fine answer of @Sisir
WordPress: version 5.7.2
PHP: version 7.4
Did you try the Permission Callback ?
According to the following 2 nice sources from the WP REST API Handbook:
REST API Handbook / Extending the REST API / Routes and Endpoints
REST API Handbook / Extending the REST API / Adding Custom Endpoints
/**
* Permission Callback function:
* 'ypp' is the Prefix I chose (ypp = Your Private Page)
*/
function ypp_get_private_data_permissions_check() {
/**
* Restrict endpoint to allowed IPs (white listing approach)
*/
$allowed_ips = array( '127.0.0.1' );
$request_server = $_SERVER['REMOTE_ADDR'];
if( ! in_array( $request_server, $allowed_ips ) )
return new WP_Error( 'rest_forbidden', esc_html__( 'Access denied from your IP address.', 'my-text-domain' ), array( 'status' => 401 ) );
return true;
};
add_action('rest_api_init', function() {
/**
* Register here your custom routes for your CRUD functions
*/
register_rest_route( 'your_private_page/v1', '/data', array(
array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'get_your_data', // <-- your main callback function
// Always allow GET, for example
'permission_callback' => '__return_true' // <-- to leave it open
),
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'insert_your_data', // <-- your main callback function
// Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.
'permission_callback' => 'ypp_get_private_data_permissions_check',
),
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => 'update_your_data', // <-- your main callback function
// Here we register our permissions callback. The callback is fired before the main callback to check if the current user can access the endpoint.
'permission_callback' => 'ypp_get_private_data_permissions_check',
),
));
});
Note:
No Plugin needed anymore. The WP REST API has been merged into WordPress core.
// oh please oh please oh please oh please oh please
I'm going thru the code, and I don't see a lot of security checking except for the use of the wordpress nonce system. As written now, that code only requires nonce's for creating a new post and submitting it via API call. It would be easy to require that for data requests.http://codex.wordpress.org/WordPress_Nonces
Remember the nonce will have to be generated at your site, sent to a user and they include it in their API request to validate their authority. A nonce is only good for two verification checks, and if unused expires in 24 hours. Its the right tool for you.