Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict access to WordPress REST API

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!

like image 766
Marc Avatar asked Aug 18 '15 21:08

Marc


People also ask

Can you restrict WordPress access?

Open the form you'd like to restrict. Then, go to Settings → Form Permissions: Check the box next to Limit form visibility. After that, choose your desired user role from the drop-down menu.

How do I block WP JSON WP v2 users?

Disable WP API with WP Hardening PluginGo to the 'Security Fixers' tab. Toggle the key next to 'Disable WP API JSON' That's all, you are done 🙂


1 Answers

This will remove all REST API endpoints for WordPress and Woocommerce for not logged in users:

function myplugin_removes_api_endpoints_for_not_logged_in() {

    if ( ! is_user_logged_in() ) {

        // Removes WordpPress endpoints:
        remove_action( 'rest_api_init', 'create_initial_rest_routes', 99 );

        // Removes Woocommerce endpoints
        if ( function_exists('WC') )
            remove_action( 'rest_api_init', array( WC()->api, 'register_rest_routes' ), 10 );
    }

} add_action('init', 'myplugin_removes_api_endpoints_for_not_logged_in');
like image 125
Caio Mars Avatar answered Sep 19 '22 20:09

Caio Mars