Search code examples
wordpresswoocommercewordpress-rest-apiwoocommerce-rest-api

WooCoommerce custom endpoint - Enable auth protection


I have defined the following custom endpoint for woocommerce:

add_action( 'rest_api_init', 'custom_endpoint' );

function custom_endpoint() {
    register_rest_route( 'wc/v3', 'my_custom_endpoint', array(
        'methods' => 'GET',
        'callback' => 'return_value',
    ) );
}

function return_value() {
    return "this is my custom endpoint!";
}

However, this endpoint is also accessible if I'm not authenticated using the ck and cs.

How can I protect it the same way all other, default endpoints of the WooCommerce API are protected? (I would prefer not needing another auth plugin for this to work, but to access it with the standard WooCommerce auth keys instead).

Thanks!


Solution

  • Hello use permission_callback with JWT Authentication for WP REST API plugin so it will work fine.

    Steps :

    1) Install JWT Authentication for WP REST API plugin 2) Set permission_callback

    Below code will work well after JWT Authentication for WP REST API plugin installation

    add_action('rest_api_init', 'custom_endpoint');
    function custom_endpoint(){
      register_rest_route('wc/v3', 'my_custom_endpoint', array(
        'methods' => 'GET',
        'callback' => 'return_value',
        'permission_callback' => function($request){      
          return is_user_logged_in();
        }
      ));
    }
    
    function return_value(){
        return "this is my custom endpoint!";
    }
    

    for more information please check JWT Authentication for WP REST API documentation.

    Checked and works well.