I’ve changed the code, the new code looks like this:
function restrict_rest_api_access($access) {
global $wpdb;
// Allow access if the user is logged in and has the 'administrator' role
if (is_user_logged_in() && current_user_can('administrator')) {
return $access;
}
// Check if the Authorization header is present and starts with "Basic "
$headers = getallheaders();
if (isset($headers['Authorization']) && strpos($headers['Authorization'], 'Basic ') === 0) {
// Decode the Authorization header (Base64 encoded)
$auth_header = base64_decode(substr($headers['Authorization'], 6));
if ($auth_header) {
list($consumer_key, $consumer_secret) = explode(':', $auth_header, 2);
// WooCommerce should handle the Basic Auth check for WooCommerce endpoints
$result = $wpdb->get_row($wpdb->prepare(
"SELECT consumer_key FROM {$wpdb->prefix}woocommerce_api_keys
WHERE consumer_key = %s LIMIT 1",
$consumer_key
));
if ($result) {
return $access; // Allow access if the consumer key is valid
}
}
}
// Otherwise, deny access to REST API
return new WP_Error(
'rest_forbidden',
__('You are not allowed to access the REST API.'),
array('status' => 403)
);
}
add_filter('rest_authentication_errors', 'restrict_rest_api_access');
We want to set our consumer secret and consumer key manually using woocommerce API KEY which we generate by Woocommerce itself NOT the key that your plugin generates.
Thanks again.