Woocommerce API not checking authorization with cache
-
I was running into a pretty serious problem where cached Woocommerce endpoints were returning without any authorization. I saw a posed solution where you pass the Authorization header into the cached API calls using
add_filter('wp_rest_cache/cacheable_request_headers', 'wprc_add_cacheable_request_headers', 10, 1);.However, I don’t want to cache for every single user and every unique token. I am serving the API to logged in users on an app.
I need for any authorized user to be able to access the woocommerce data while locking out anyone else. I am using the JWT Authentication for WP REST API to authenticate my users, but if someone had a similar requirement with a different auth i’m sure this solution could be implemented.
This solution isn’t the best, and I’m wondering what other sort of solutions can be implemented in the future, but the current solution works well enough for me. Sharing so others might find useful.
Ideally the final solution doesn’t require me to have to modify any core plugin files (or even adding my own instead?)
I modified wp-rest-cache.php, the plugin file created in the MU folder open creation. I saw a ticket posted months ago where Richard provided this solution and I used that as my starting point.
Paste this code at line 33
// if jwt auth plugin is used // check to make sure all WC calls are authenticated if(is_plugin_active('jwt-authentication-for-wp-rest-api/jwt-auth.php')) { include_once WP_PLUGIN_DIR . '/jwt-authentication-for-wp-rest-api/jwt-auth.php'; $plugin_name = 'jwt-auth'; $version = '1.1.0'; $rest_prefix = trailingslashit( rest_get_url_prefix() ); $request_uri = esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ); $woocommerce = ( false !== strpos( $request_uri, $rest_prefix . 'wc/' ) ); $third_party = ( false !== strpos( $request_uri, $rest_prefix . 'wc-' ) ); if($woocommerce || $third_party) { // check for validation $jwt = new Jwt_Auth_Public($plugin_name, $version); $valid_token = $jwt->validate_token(); if(is_wp_error($valid_token)) { // authorization failed for whatever reason return; } } }
The topic ‘Woocommerce API not checking authorization with cache’ is closed to new replies.