CakePHP Auth how to allow specific controller and actions

30,763

Solution 1

The period will not work. You could try '/' instead. If that fails as well, you should set $this->Auth->allow('index') in PostController's and UserController's ::beforeFilter() individually. Don't forget to call parent::beforeFilter().

Solution 2

Depends on the version you're working on. If it's cakephp 2.x, put this code into the controller that has the action you want give access without login. As your question, you should put this code to Posts controller:

function beforeFilter(){
     $this->Auth->allow(array('index','another action'));}

allow(array('acction you want to allow')) instead allow('acction you want to allow')

Solution 3

For Cakephp 2.x, there are several methods (depending on the cakephp version).

From the docs (http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html):

// Allow all actions. CakePHP 2.0
$this->Auth->allow('*');

// Allow all actions. CakePHP 2.1
$this->Auth->allow();

// Allow only the view and index actions.
$this->Auth->allow('view', 'index');

// Allow only the view and index actions.
$this->Auth->allow(array('view', 'index'));

Solution 4

In cake 3.x you can use below lines of code to allow all the actions.

    public function beforeFilter(Event $event) {
      parent::beforeFilter($event);
      $this->Auth->allow();
    }

Solution 5

I am using CakePHP 2.x. The slash trick doesn't work.

If you want to allow user access "myController.myAction" without login, you should add beforeFilter() into myController.php instead of AppController.php

Here is the code to add into myController.php:

function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('myAction');
}
Share:
30,763
Silvan Mudbind
Author by

Silvan Mudbind

Updated on January 02, 2020

Comments

  • Silvan Mudbind
    Silvan Mudbind over 4 years

    I have a "Posts" and a "Users" controller. I use the Auth Component and I want that all users can visit "Post.index" but only logged in users can visit "User.index".

    In my app_controller.php I have this

    $this->Auth->allow('signup', 'confirm', 'index');
    

    but with that all users can visit post.index and user.index. How can I specify a Controller in the allow-method?

    This didn't work for me:

    $this->Auth->allow('signup', 'confirm', 'Post.index');
    

    update I removed 'index' from the app_controller.php and instead set it in the beforeFilter method in the post controller:

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

    I also set a variable "loggedIn" in app_controller, without calling "parent::beforeFilter();" I got an "undefined variable" notice.

    thx sibidiba