Is there a way that I can restrict access to url calls made to WP REST API? I am using WP REST API to create AJAX feeds that can be accessed through the URL. They are formatted like this: http://example.com/wp-json/posts?type=post&filter[posts_per_page]=10
The problem is that anyone can add /wp-json/posts?type=post&filter[posts_per_page]=10
to the end of my URL and retrieve a feed of this information. I want to turn this off when users are not logged into WordPress doing something like this:
if ( !is_user_logged_in()) {
// Turn off REST API feed
}
Or, I would like to add some kind of authentication that needs to be added to mask the api.
I found something like this online but I have not had any luck getting it to work. I added it to a custom plugin. Unfortunately I am still able to access the feed when not logged in.
add_action( 'init', function() {
global $wp_post_types;
$wp_post_types['post']->show_in_rest = is_user_logged_in();
}, 20 );
I am worried that there is no way to make a connection between activating the API and making the HTTP request on the front end. Am I thinking about this wrong? Has anyone run into this problem?
Thanks!
The problem and blessing of WordPress is that it allows too much flexibility, particularly when the platform provides a clean method: Require Authentication for all requests
To be fair, this is hidden in the frequently asked questions.
Edit: To exclude jwt-auth
This will remove all REST API endpoints for WordPress and Woocommerce for not logged in users:
This will block the entire REST API for anyone not logged in:
Standard caveat that this just turns off REST, nothing else. Make sure it has enough priority to come after other
determine_current_user
filters. Did not test on multi site.You can add other tests to the conditional as well, if you want to filter by URL or other factors.