2

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;
    }
}
  • I came across your question when searching for a solution to mine. My permission callback is being called 4 times. – anastymous Aug 15 '18 at 4:19
0

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 :/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.