15 Oct 2009

CakePHP Auth Component Problem

cakephp

I’ve been using CakePHP for my last few projects and recently ran into a problem that was driving me nuts. I have a few pages that don’t require any authentication. You can allow pages to be viewed by calling $this->Auth->allow(‘function_name’) in your beforeFilter() method. So, I set up my app_controller class with a before filter that looks something like this.

<?php

class AppController extends Controller {

    var $helpers = array('Html', 'Form', 'Javascript');
    var $components = array('Auth');

    function beforeFilter() {
        $this->Auth->autoRedirect = false;
        $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
        $this->Auth->allow('display');
    }

}

?>

‘Display’ is a method in the pages controller, so all static pages can be shown without authentication. This works fine, on to my contact controller which is also allowed to be accessed without authentication. I set up my contact controller and wanted to allow the index method to be displayed. In the contact controller you call the parent beforeFilter() and then allow any additional methods like so:

function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('index');
}

But for some reason, this kept sending me to the login form to authenticate. After banging my head on the wall I soon remembered my view was calling an element that used a method from another controller. Long story short, Auth was not allowing this method without authentication. Unfortunately, even with debug mode turned on, there was no clue to lead me in the right direction.

So, if you run into a similar problem, make sure you allow any related controller functions to run without authentication if you are using elements and requestActions.

One Response to “CakePHP Auth Component Problem”

Leave a Reply