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

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

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目