首页 > 解决方案 > Cakephp 4 - 实现每个路由的授权

问题描述

我有管理任务的特定路线(/admin/...)。用户在组中(管理员,用户)

使用授权插件,只允许管理员用户访问 /admin 路由的简单方法是什么?

有政策可以吗?

谢谢

标签: cakephp

解决方案


这是我的解决方案,如果我能改进它,请告诉我:

我创建了一个策略:

class UserPolicy
{
    /**
     * Check if $user have admin access
     *
     * @param Authorization\IdentityInterface $user The user.
     * @param App\Model\Entity\Users $u
     * @return bool
     */
    public function canAdminAccess(IdentityInterface $user, $u)
    {
        return (bool)($user->group_id === GROUP_ADMIN);
        return false;
    }
}

在每个管理控制器中,在 beforeFilter 方法中,我调用授权:

public function beforeFilter(EventInterface $event)
{
    parent::beforeFilter($event);
    $this->Authorization->authorize($this->user,'adminAccess');
}

推荐阅读