7

I have a WordPress website which I use just to populate blog posts and some private posts under custom post types. In another website, I am using the REST API to display the posts. If I use software like Postman, I can display data from the REST API.

How can I prevent any unauthorized REST API requests to domain www.example.com ? so if the request is not coming from www.mysite.com, it is blocked?

Basically prevent my custom post types (example.com) to be visible to the rest api if it is not coming from mysite.com

Rain Man
  • 1,163
  • 2
  • 16
  • 49

3 Answers3

8

You can Disable External request by adding this in your wp-config.php ( Also, you can specify domain which you don't want to block like this).

 define( 'WP_HTTP_BLOCK_EXTERNAL', TRUE );
 define( 'WP_ACCESSIBLE_HOSTS', 'example.com, domain.com' );
T.Todua
  • 53,146
  • 19
  • 236
  • 237
Jigar
  • 3,055
  • 1
  • 32
  • 51
  • 2
    To be able to update WordPress core, plugins and themes that are from `https://wordpress.org/themes/` make sure to add `api.wordpress.org` to `WP_ACCESSIBLE_HOSTS`. If you use a theme **not** hosted on `https://wordpress.org/themes/` contact the theme author and ask for the domain where the theme files are being downloaded from. – lowtechsun Jul 18 '19 at 13:08
5
apply_filters( 'rest_authentication_errors', WP_Error|null|bool )

Filters REST authentication errors.Put code in functions.php in your theme directory.

Complete description : https://developer.wordpress.org/reference/hooks/rest_authentication_errors/

add_filter( 'rest_authentication_errors', 'wpse150207_filter_incoming_connections' );

function wpse150207_filter_incoming_connections( $errors ){

    $allowed_ips = array( '127.0.0.1' );
    $request_server = $_SERVER['REMOTE_ADDR'];

    if( ! in_array( $request_server, $allowed_ips ) )
        return new WP_Error( 'forbidden_access', 'Access denied', array( 'status' => 403 ) );

    return $errors; 

}
Vasim Shaikh
  • 4,485
  • 2
  • 23
  • 52
2

One way to restrict REST requests is to hook at rest_api_init with priority 1, and whitelist the IP's you want. In this example, I restrict REST access to the server itself only:

/**
*    Disables WordPress Rest API for external requests
*/
add_action('rest_api_init', function() {
    $whitelist = ['127.0.0.1', "::1"];

    if(!in_array($_SERVER['REMOTE_ADDR'], $whitelist)){
        die('REST API is disabled.');
    }
}, 1);
Lucas Bustamante
  • 15,821
  • 7
  • 92
  • 86