Rain Man
Rain Man

Reputation: 1263

Restrict WordPress Rest API requests to my domain

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

Upvotes: 7

Views: 7114

Answers (3)

Lucas Bustamante
Lucas Bustamante

Reputation: 17178

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);

Upvotes: 2

Jigar
Jigar

Reputation: 3261

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' );

Upvotes: 8

Vasim Shaikh
Vasim Shaikh

Reputation: 4512

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; 

}

Upvotes: 6

Related Questions