Search code examples
ajaxsymfonyauthorizationaccess-control

Symfony 2 - Secure Ajax Controller


I have ajax controler to store actions that are called through the AJAX from JS.

Here in every action I validate if request is made by AJAX and no other:

if (!$request->isXmlHttpRequest()) {
    return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}

Now the problem is that not every ajax controller action should be called by everyone, but rather depending on a role of the logged in user.

The request to action is made by AJAX from JS, but since actions are in controller I am still able to get logged in user object by $this->getUser() and to check if user has acceptable ROLE to execute the controller action by isGranted().

Example:

if (!$authorizationChecker->isGranted('ROLE_ADMIN')) {
    return new JsonResponse(array('message' => 'This can be performed only by admin!'), 400);
}

Should I check ROLES from inside controller in every action or try to configure access_control for ajax routes in security.yml?

I have no idea what is the big difference between these two approaches, but would like to know which one would be more practical and could keep my ajax actions more secure.


Solution

  • Depends on the number of AJAX Controllers you have. If you have so many controllers those are to be allowed only for a certain role, access_control in security.yml is a good choice. Else you can have the condition in each controller.

    For dynamic permission layer, where permission to be decided based on subject attribute(the viewing content), You might want to use voter.