【问题标题】:Cakephp 3.6.14: redirect after action denyCakephp 3.6.14:动作拒绝后重定向
【发布时间】:2019-01-30 08:42:31
【问题描述】:

我正在尝试deny 为我的控制器中的非管理员用户执行一些操作。所以在控制器中我使用了这段代码:

public $components = array('Auth');

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    if($this->Auth->user('role_id')==1 or $this->Auth->user('role_id')==2){ //role: 1 admin, 2 project manager
        $this->set('is_admin', true);
    }
    else
    {            
        $this->Auth->deny(['index','delete']);
        $this->set('is_admin', false);            
    }        

    $this->set('my_id', $this->Auth->user('id'));
}

因此,现在只要不是管理员或项目经理的用户尝试执行indexdelete 操作,就会被重定向到“方法不允许”错误页面。但是我想返回上一页并显示一条消息:“您无权执行此操作”。

我尝试在 AppController 中设置'unauthorizedRedirect' => $this->referer()

  $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ],
            'unauthorizedRedirect' => $this->referer()
        ]); 

但是没有用。我设法实现这一点的唯一方法是在控制器的beforeFilter 函数中使用此代码:

 if(!($this->Auth->user('role_id')==1 && !$this->Auth->user('role_id')==2 && ($this->request->action === 'index' || $this->request->action === 'delete')){
        $this->Flash->error(__('You are not authorized to perform this action'));
        return $this->redirect(['controller' => 'Users', 'action' => 'index']);
    }

但在我想拒绝某些操作的所有控制器中,这似乎不是正确的方法。还有其他方法吗?

【问题讨论】:

  • 你可能想研究一个更干净的解决方案,比如tinyauth,代码更少,可能更安全。

标签: php cakephp authorization cakephp-3.x


【解决方案1】:

Cakephp 也提供了isAuthorized 函数。你可以利用它。 只需在您的 App 控制器或单独的控制器中定义 isAuthorized(如果您想为每个控制器设置单独的条件。)

 public function isAuthorized($user)
    {
        $roleArray = [1, 2]; // your role ids array
        if ( !in_array($user['role_id'], $roleArray) && in_array($this->request->getParam('action'), ['index', 'delete'])) {  // put your conditions here
           return false;
        }
      return true;
    }

Cakephp -> Authentication and Authorization -> Authorization (who’s allowed to access what)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-31
    • 2015-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多