WooCommerce 自定义端点 - 启用身份验证保护

WooCoommerce custom endpoint - Enable auth protection

我已经为 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!";
}

但是,如果我没有使用 ck 和 cs 进行身份验证,也可以访问此端点。

如何像保护 WooCommerce API 的所有其他默认端点一样保护它? (我宁愿不需要另一个身份验证插件来工作,而是使用标准的 WooCommerce 身份验证密钥访问它)。

谢谢!

您好,请将 permission_callbackJWT Authentication for WP REST API 插件一起使用,这样它就可以正常工作了。

步骤:

1) 安装 JWT Authentication for WP REST API 插件 2) 设置permission_callback

下面的代码在 JWT Authentication for WP REST API 插件安装后可以正常工作

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!";
}

有关详细信息,请查看 JWT Authentication for WP REST API 文档。

已检查并且运行良好。

Cookie 身份验证是 WordPress 附带的标准身份验证方法。当您登录到您的仪表板时,这会为您正确设置 cookie,因此插件和主题开发人员只需要有一个 logged-in 用户。

例如,built-in Javascript 客户端是这样创建随机数的:

<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array(
    'root' => esc_url_raw( rest_url() ),
    'nonce' => wp_create_nonce( 'wp_rest' )
) );

然后在基本模型中使用:

options.beforeSend = function(xhr) {
    xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);

    if (beforeSend) {
        return beforeSend.apply(this, arguments);
    }
};

这里是编辑 post 标题的示例,使用 jQuery AJAX:

$.ajax( {
    url: wpApiSettings.root + 'wp/v2/posts/1',
    method: 'POST',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
    },
    data:{
        'title' : 'Hello Moon'
    }
} ).done( function ( response ) {
    console.log( response );
} );

请注意,您无需验证随机数在您的自定义端点内是否有效。这是自动为您完成的 rest_cookie_check_errors()

Woocommerce API

https://woocommerce.github.io/woocommerce-rest-api-docs/?php#authentication-over-https

While cookie authentication is the only authentication mechanism available natively within WordPress, plugins may be added to support alternative modes of authentication that will work from remote applications.

根据官方文档:https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins