Permission Check for REST API Endpoint Runs Twice?

I’m making a plugin using the WP REST API, and everything seems to be working as expected. However, there is behavior I don’t understand. The authPermissionCheck() method is executed twice for each request before output is generated – first here and then here. It just seems inefficient. Does anyone understand why?

Here’s the relevant portion of my plugin code (stripped down):

class My_REST_Controller
{
    public function __construct()
    {
        add_action( 'rest_api_init', function()
        {
            $this->user = wp_get_current_user();

            register_rest_route( 'myplug/v1', '/auth', array(
                array(
                    'methods'  => \WP_REST_Server::READABLE,
                    'callback' => array( $this, 'authenticate' ),
                    'permission_callback' => array( $this, 'authPermissionCheck' )
                )
            ));
        });
    }

    // This method is called twice when the
    // auth endpoint is hit. Why?
    public function authPermissionCheck()
    {
        if ( ! user_can( $this->user, 'read' ) ) {
            return new \WP_Error( 'rest_forbidden', esc_html__(
                'No permission.', 'my-text-domain' ),
                array( 'status' => 401 )
            );
        }
        return false;
    }
}

1 Answer
1

Apparently, it’s by design.

https://github.com/WP-API/WP-API/issues/2400

Permission callback is run once for the Allows header, and the second time for the callback itself.

Didn’t dug enough through it to understand why :/

Leave a Comment