Simple use of route prefixes within AuthComponent in a CakePHP App

In any regular website you have a restricted area for management, and a public webpage.
When writing a CakePHP app you would usually use the AuthComponent for authentication, and for allowing and denying actions. A boring task of using Auth is that you have to define in every controller that has public actions the allowed actions in that controller, it can be done by overriding the beforeFilter() method or by using any other technique, like looking for any defined variable with the allowed actions names and handle it in the AppController::beforeFilter(), or you can do it automatically! Yes, you can can assume a convention telling that every restricted action has a route prefix. So you won’t need to define any additional information on each controller.
The authorization logic for allowing users to reach a specified action is then set in the AppController::beforeFilter() by playing with the $this->params[‘prefix’] value.

A simple example is shown below:

We enable a single route prefix by editing app/config/core.php

	Configure::write('Routing.prefixes', array('admin'));

Then we edit our app/app_controller.php

class AppController extends Controller {

    public function beforeFilter () {
        if (empty($this->params['prefix'])) {
        } else {
            $this->layout = 'admin';


The example above checks for an non prefixed request (following our own conventions, it’ll be a public action), and if it is non prefixed just allow it, for example:

In other hand, if it is prefixed and there’s not a logged in user, it is not allowed, being denied by default.
So if a not logged user tries to request for:

He is immediately redirected to the AuthComponent logoutRedirect url.

It’s just a very simple tip, i hope it helps someone :-D

  1. Smart and short! Thanks for sharing!

    • Hayden Thring
    • March 25th, 2011


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: