首页 > 解决方案 > 没有身份的cakephp授权错误

问题描述

我使用带有授权 2 插件的 cakephp 4。我有一个检查用户是否具有“管理员”角色的策略。

当在应用程序上识别用户=> 设置身份时,它可以正常工作。

但是当用户未被识别时 => 身份为空

对策略的调用返回错误:

Argument 1 passed to App\Policy\UserPolicy::canAdminAccess() must be an instance of Authorization\IdentityInterface, null given

策略函数:($user 未识别时为空)

public function canAdminAccess(IdentityInterface $user)
    {
        return (bool)($user->group_id === 1);
        return false;
    }

以及控制器中的调用:

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

关于如何解决这个问题的任何想法?

谢谢

标签: cakephp

解决方案


授权取决于身份验证,当用户未通过身份验证时,通常没有必要让他们继续进行授权检查。

我建议您考虑将身份验证组件的identityCheckEvent选项从默认Controller.startup(发生在 之后 Controller::beforeFilter())更改为Controller.initialize(这是调用Controller::beforeFilter()):

$this->loadComponent('Authentication.Authentication', [
    'identityCheckEvent' => 'Controller.initialize',
]);

这将检查组件beforeFilter()回调中的标识,该回调在控制器回调之前被调用beforeFilter()

beforeFilter()或者,您可以在您的方法中自己检查身份:

// ...

if (!$this->Authentication->getIdentity()) {
    throw new UnauthenticatedException(
        $this->Authentication->getConfig('unauthenticatedMessage', '')
    );
}

// ...

$this->Authorization->authorize($this->user, 'adminAccess');

请注意,对于应该允许在没有身份验证的情况下访问的操作,您需要确保既不应用身份验证检查,也不应用授权检查!就像是:

$unauthenticatedAllowed = in_array(
    $this->request->getParam('action'),
    $this->Authentication->getUnauthenticatedActions(),
    true
);

// ...

if (!$unauthenticatedAllowed) {
    if (!$this->Authentication->getIdentity()) {
        throw new UnauthenticatedException(
            $this->Authentication->getConfig('unauthenticatedMessage', '')
        );
    }

    // ...

    $this->Authorization->authorize($this->user, 'adminAccess');
}

此时您可能还想问自己将公共端点与受保护端点分开是否有意义,例如将它们放在单独的控制器和/或前缀中,以便您可以仅在受保护的端点,而让公共端点没有任何身份验证/授权检查。

也可以看看


推荐阅读