duansha3771 2017-11-02 16:44
浏览 155
已采纳

WP REST API不需要在POST上进行身份验证

I created a custom route to edit a single user meta value. Here is the code:

add_action( 'rest_api_init', function () {
    register_rest_route( 'custom', '/activating/(?P<id>\d+)', array(
        'methods' => 'POST',
        'callback' => __NAMESPACE__ . '\\activate_user',
        'args' => array(
            'id' => array(
                'validate_callback' => function($param, $request, $key) {
                    return is_numeric( $param );
                }
            ),
        ),
    ));
});

function activate_user($data){
    $user_id = $data['id'];
    update_user_meta( $user_id, "user_active", 1, 0 );
    return array( 'message' => 'OK' );
}

Testing it on Postman, WP not required authentication. This is normal? What I need to do to allow POST request only with authentication?

  • 写回答

1条回答 默认 最新

  • drpqxogph15436713 2017-11-02 17:09
    关注

    You should use the permission_callback argument to authenticate the user.

    add_action( 'rest_api_init', function () {
        register_rest_route( 'custom', '/activating/(?P<id>\d+)', array(
            'methods' => 'POST',
            'callback' => __NAMESPACE__ . '\\activate_user',
            'permission_callback' => 'is_user_logged_in',
            'args' => array(
                'id' => array(
                    'validate_callback' => function($param, $request, $key) {
                        return is_numeric( $param );
                    }
                ),
            ),
        ));
    });
    

    As you can see here, I passed in the is_user_logged_in function which will just do a basic (bool)true or false if the user is logged in or not. You could take it further by checking for capabilities and verifying nonces (if nonce is passed in the headers).

    Source

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题