I have created custom API, which is working fine, but I am not able to authenticate it, it returns result without checking for keys
I have created consumer key and secret key from admin.
How to validate request to API.
I tried one solution, which is working as expected but my question is,
what is the standard way of authentication custom API
my current solution
require_once '/woocommerce/includes/legacy/api/v1/class-wc-api-authentication.php';
$test = new WC_API_Authentication();
$user = wp_get_current_user();
$test->authenticate($user);
1 Answer
When working with the API recently I found if the authentication header with the consumer key as the username and the consumer secret as the password is present and valid this sets the current user global as the matched user.
I found the core executes the REST route until current_user_can is called, at which point if the header was missing or invalid the current user ID is 0 and as ‘current user cant’, this prevents the request from further processing.
Looking at your solution, $user need not be defined as it is unused by the WC_API_Authentication::authenticate() method.
If this fixed your code, it would suggest you haven’t registered a REST route (/wp-json/wc/v1/my-route) and have defined a custom handling of the request yourself.
You may wish to look at the ‘woocommerce_api_endpoints’ filter instead.