Restrict WordPress Rest API requests to my domain
Asked Answered
V

3

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

Viperine answered 13/2, 2019 at 1:13 Comment(1)
Check this out for WP REST API authentication v2.wp-api.org/guide/authenticationSherleysherline
M
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' );
Mccallister answered 18/2, 2019 at 6:22 Comment(1)
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.Quiteris
D
6
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; 

}
Danica answered 20/2, 2019 at 9:29 Comment(0)
K
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);
Kareem answered 24/2, 2019 at 13:36 Comment(1)
this action does not seem to work in my wp installation - I placed in theme's function.php but no effectsNeurology

© 2022 - 2024 — McMap. All rights reserved.