Handling AJAX authorization failures within CakePHP AuthComponent

A quick snippet of code to help with CakePHP AuthComponent.

Lately, I’ve been spending a lot of time back in the web development world and with my teenage excitement for the whole experience. Something that I haven’t felt for a while … I’ve been working on a client project which uses CakePHP for an internal system. This project uses the latest version of CakePHP to date (3.1.6 at writing) and I’m incorporating the AuthComponent for access control.

I ran into two main issues:

  1. My initial AuthComponent configuration along with a custom Authorize object resulted in a redirect loop when an the user didn’t have sufficient rights.This was easily remedied by adding an ‘unauthorizedRedirect’ configuration to AuthComponent which pointed to a public action.
  2. When making AJAX calls to an unauthorized action I was receiving the message

    “Template file “Dashboard/json/index.ctp” is missing”

    DashboardController::index() is my public action. However because I have the RequestHandlerComponent enabled, it’s trying to respond with a json response. Regardless, I just want it to tell me I’m unauthorized.

    Inside my custom authorize object I added:

    if($request->is("ajax") && !$authorized) {
    throw new UnauthorizedException();
    }

    Where $authorized is calculated earlier in the function. Now when an AJAX call is made I get the expected unauthorized response.

Thanks for reading and hopefully that helped someone. Please comment on alternate strategies or if you just want to comment..

Leave a Comment