首页 > 解决方案 > CakePHP 4 身份验证插件,允许访问除 admin 目录之外的所有目录

问题描述

我正在为网站构建一个非常简单的 CMS 后端,我选择使用 CakePHP 4。我想知道是否有办法允许访问网站的所有部分,除非它们位于 Controller/Admin/ 目录中(所有行政控制都将发生)。

在文档中,它显示了这个例子:

public function beforeFilter(\Cake\Event\EventInterface $event)
{
    parent::beforeFilter($event);
    // for all controllers in our application, make index and view
    // actions public, skipping the authentication check
    $this->Authentication->addUnauthenticatedActions(['view', 'index']);

}

所以我可以添加无需身份验证就允许的控制器操作,但是由于我已将登录名与 /Admin/ 前缀分开,有没有办法只允许 /Admin/ 前缀中的所有内容?

谢谢

标签: cakephp

解决方案


尝试实现请求授权中间件

https://book.cakephp.org/authorization/2/en/request-authorization-middleware.html

喜欢:

public function canAccess($identity, ServerRequest $request)
{
    if ($request->getParam('prefix') !== 'Admin') {
        return true;
    }

    if (
        $identity &&
        $request->getParam('prefix') === 'Admin' &&
        in_array($request->getParam('action'), ['add', 'edit'])
    ) {
        return true;
    }

    return false;
}

推荐阅读