CakePHP Auth如何允许特定的控制器和操作

时间:2010-05-08 10:03:25

标签: authentication cakephp controller

我有一个“帖子”和一个“用户”控制器。我使用Auth组件,我希望所有用户都可以访问“Post.index”,但只有登录用户才能访问“User.index”。

在我的app_controller.php中我有这个

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

但是所有用户都可以访问post.index和user.index。如何在allow-method中指定Controller?

这对我不起作用:

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

更新 我从app_controller.php中删除了'index',而是将其设置在post控制器的beforeFilter方法中:

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

我还在app_controller中设置了一个变量“loggedIn”,而没有调用“parent :: beforeFilter();”我收到了一个“未定义的变量”通知。

thx sibidiba

8 个答案:

答案 0 :(得分:13)

期限不起作用。你可以试试'/'。如果失败,您应该分别在PostController和UserController的$this->Auth->allow('index')中设置::beforeFilter()。不要忘记调用parent :: beforeFilter()。

答案 1 :(得分:2)

取决于您正在处理的版本。如果是cakephp 2.x,请将此代码放入控制器中,该控制器具有您希望无需登录即可访问的操作。作为您的问题,您应该将此代码添加到帖子控制器:

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

allow(array('acction you want to allow'))代替allow('acction you want to allow')

答案 2 :(得分:1)

我正在使用CakePHP 2.x.斜杠技巧不起作用。

如果你想在没有登录的情况下允许用户访问“myController.myAction”,你应该将beforeFilter()添加到myController.php而不是AppController.php

以下是要添加到myController.php中的代码:

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

答案 3 :(得分:1)

对于Cakephp 2.x,有几种方法(取决于cakephp版本)。

来自文档(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'));

答案 4 :(得分:1)

CakePHP开发人员常见的问题是授权特定控制器的特定操作

https://blog.sohelrana.me/cakephp-auth-allow-specific-actions-specific-controllers/

答案 5 :(得分:1)

在cake 3.x中,您可以使用以下代码行来允许所有操作。

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

答案 6 :(得分:0)

$ this-> name返回当前的Controller请求。

在AppController :: beforeFilter()

中尝试此操作
public function beforeFilter()
{

    // ... Basic configs 

    switch ($this->name) {
        case 'Posts':
            $this->Auth->allow('add');
            break;              
        case 'Test':
            $this->Auth->allow('test');
            break;
    }
}

抱歉,我的英语不好

答案 7 :(得分:0)

对于 CakePHP 3。* ,可以在特定控制器

允许特定方法
//put this line after namespace
use Cake\Event\Event;

// in your specific controller call this function to allow specific methods
public function beforeFilter(Event $event) {
        parent::beforeFilter($event);
        $this->Auth->allow(['index','view']); //<-- here you put your methods
}
相关问题