首页 > 解决方案 > 无需用户登录和权限回调的 WP REST API creting 和端点

问题描述

我使用 WP REST API 创建了一个新端点,用于添加、修改或删除购物车中的商品。我已经使用随机数作为安全措施。随机数在 PHP 中设置,并由 Javascript 的标头重新发送。我假设它们是由 WP 自动检查的。在我的示例中,我假设默认情况下未登录用户。那么,在这种情况下,我应该在 permissioms 回调中使用哪些权限?如何保护端点不被滥用?在我看来,仅使用权限回调中的“返回真”很明显,但如果我遗漏了什么,有人可以提出建议吗?谢谢

 wp_localize_script( 'mis-cursos-stripe-script', 'mis_cursos_stripe_namespace', array(
    'url'    => rest_url( '/mis_cursos/checkout_session' ),
    'url_cart' => rest_url( '/mis_cursos/cart' ),
    'nonce'  => wp_create_nonce( 'wp_rest' ),
) );


const nonce = mis_cursos_stripe_namespace.nonce;
const headers = new Headers({
            'Content-Type': 'application/json',
            'X-WP-Nonce':  nonce,
            'X-mis-cursos': 'mis_cursos', // header data string
        });

来自 WP CODEX 的示例:

https://developer.wordpress.org/rest-api/extending-the-rest-api/routes-and-endpoints/#permissions-callback

if ( ! current_user_can( 'edit_posts' ) ) {
    return new WP_Error( 'rest_forbidden', esc_html__( 'OMG you can not view private data.', 'my-text-domain' ), array( 'status' => 401 ) );
}

// This is a black-listing approach. You could alternatively do this via white-listing, by returning false here and changing the permissions check.
return true;

标签: wordpressrest

解决方案


推荐阅读