• Resolved npittet

    (@npittet)


    Hello,

    For security reasons I have blocked access to the REST API for all users who are not logged in.

    This seems to be a problem for WP Statistics, even access to the REST API is not included in the requirements: https://wp-statistics.com/resources/wp-statistics-requirements/

    I’ve tried whitelisting my server IP, but it doesn’t work. Does anyone know how to do this?

    Below is the script used to block access to the REST API:

    <?php
    // disable REST API (wp-json) to external requests / 17.6.2024 ok for WP Statistics
    add_action( 'rest_api_init', 'restrict_rest_api_to_localhost', 0 );
    function restrict_rest_api_to_localhost() {
    if(!is_admin()) {
    $whitelist = [
    '127.0.0.1',
    "::1",
    "192.1.1.1", // my server IP
    ];
    $message = "REST API is disabled.";
    if( ! in_array($_SERVER['REMOTE_ADDR'], $whitelist ) ) {
    die( $message );
    }
    }
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Support Amir

    (@amirfallah)

    Hi,

    Thank you for bringing this issue to our attention. The document indeed needed updating.

    For this scenario, you can use the following code:

    add_filter('rest_authentication_errors', 'allow_rest_api_for_local_ips');

    function allow_rest_api_for_local_ips($errors)
    {
    // if there is already an error, just return it
    if (is_wp_error($errors)) {
    return $errors;
    }

    $whitelist = array(
    '127.0.0.1',
    // etc
    );

    if (!in_array($_SERVER['REMOTE_ADDR'], $whitelist)) {
    // return WP_Error object if user is not logged in
    return new WP_Error('no_rest_api_sorry', 'REST API not allowed', array('status' => 401));
    }

    return $errors;
    }

    Please let me know if you have any further questions or need assistance.
    Regards,

    Thread Starter npittet

    (@npittet)

    Hi Amir,

    Thank you for your answer. I added in $whitelist my server IPs (IP V4 + V6), but it doesn’t seem to be working. I can’t see any users online in the stats.

    Is anyone having the same problem?

    Plugin Author Mostafa Soufi

    (@mostafas1990)

    Hi, thank you for repying.

    First, please ensure that the front-end is successfully sending the request with this change. You can verify this by checking the browser console (Network → XHR).

    Once confirmed, we can continue debugging.

    Best

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.