首页 > 解决方案 > CakePHP - 处理未授权但已登录的用户

问题描述

我在一个 CakePHP 网站上工作,但是我在它的授权部分遇到了一些问题。如果我有一个登录用户尝试访问不允许他们访问的资源,则会引发禁止的异常。我需要这个重定向到一个友好的页面,说明它们是不允许的以及为什么。我可以在不设置全局错误 403 页面的情况下执行此操作吗?

标签: phpcakephp

解决方案


检查授权说:

当权限被拒绝时,authorize() 方法将引发 Authorization\Exception\ForbiddenException。 如果要检查授权并获得布尔结果,可以使用 can() 方法:

if ($this->Authorization->can($article, 'update')) {
    // Do something to the article.
} else {
    $this->Flash->error('Your error message here');
    // or set view vars:
    // $not_authorized = [
    //    'title' => '...',
    //    'reson' => ...,
    //    'solution' => ....
    // ];
    // $this->set('not_authorized', $not_authorized);
    $this->render('not_authorized');

}

推荐阅读