Search code examples
phpjqueryajaxsymfonysymfony-routing

Restrict routes to a Ajax call, it's possible in Symfony 2.6+?


I'm looking the best way to achieve "automatic" routing restriction to Ajax calls. Right now I'm doing as follow:

/**
 * @Secure(roles="IS_AUTHENTICATED_FULLY")
 * @Route("/someRoute", name="someRoute")
 * @Method("POST")
 */
public function eliminarFacturasAction(Request $request)
{
    $response['success'] = false;
    $status              = 400;

    if ($request->isXmlHttpRequest()) {
        // needs to set $response values and $status=200 all the time
    } else {
        // needs to handle the exception and return Json response
    }

    return new JsonResponse($response, $status ?: 200);
}

In order to avoid this could I use this instead?

 @Route("/someRoute", 
           name="routeName", 
           condition="request.headers.get('X-Requested-With') == 'XMLHttpRequest'"
 )

I'm using jQuery as only JS framework so XMLHttpRequest wont be a problem. What kind of exception will be trigger if route isn't executed through Ajax call? Can I catch it and show message to users? Or show some kind of 404 page?

I have found a similar question here but is not clear for me at all


Solution

  • You could do so in a kernel.request listener.

    class DisallowNonXmlHttpRequestListener
    {
        public function checkRequest(GetResponseEvent $event)
        {
            if (!$event->getRequest()->isXmlHttpRequest()) {
                throw new AccessDeniedHttpException();
            }
        }
    }
    

    And in your services config:

    services:
        disallow_non_xml_http_request_listener:
            class: DisallowNonXmlHttpRequestListener
            tags: [{ name: kernel.event_listener, event: kernel.request, method: checkRequest }]