Search code examples
phpwordpresswordpress-rest-api

WP REST API not required authentication on 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?


Solution

  • 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