We wanted to stop this leaking all our posts but also allow it for certain purposes with a username and password. Some solutions are very heavy-handed and can cause issues with plugins etc if you simply disable it all! With this method you can just lock down certain endpoints that you are worried about.

This also allows access for logged-in WordPress users, but you could simply remove that section if needed.

    // remove access to /wp-json/wp/v2/posts without auth
    function custom_rest_api_authenticate($result) {
        // Check if the request contains the 'Authorization' header.
        $authorization = getallheaders()['Authorization'] ?? '';
    
        // Extract the base64-encoded credentials from the 'Authorization' header.
        $credentials = explode(' ', $authorization);
    
        // Check if the request path matches the '/wp-json/wp/v2/posts' endpoint.
        $request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
        $is_posts_endpoint = strpos($request_path, '/wp-json/wp/v2/posts') !== false;
    
        if ($is_posts_endpoint && isset($credentials[1])) {
            $decoded_credentials = base64_decode($credentials[1]);
            list($username, $password) = explode(':', $decoded_credentials);
    
            $expected_username = 'your_username';
            $expected_password = 'your_password';
    
            if ($username === $expected_username && $password === $expected_password) {
                // Authentication successful for the /posts endpoint.
                return $result;
            }
        }
    
        // Check if the user is already logged in.
        if (is_user_logged_in()) {
            // Allow access for logged-in users.
            return $result;
        }
    
        // Authentication failed for the /posts endpoint. Return a 401 Unauthorized response.
        if ($is_posts_endpoint) {
            return new WP_Error('rest_not_authorized', 'Authentication failed.', array('status' => 401));
        }
    
        return $result; // Allow access to other parts of the REST API.
    }
    
    add_filter('rest_authentication_errors', 'custom_rest_api_authenticate');  
Last modified: September 27, 2023

Author

Comments

Write a Reply or Comment

Your email address will not be published.