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个回答

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

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐