【问题标题】:Using Authorization plugin CakePHP 4.2 Controller pointing a different model使用授权插件 CakePHP 4.2 Controller 指向不同的模型
【发布时间】:2021-09-22 19:54:39
【问题描述】:

我被这个问题困住了。

帐户控制器管理用户表中的所有内容。但是当我调用它时,得到了错误 The request to *** did not apply any authorization checks

所以,How can i use the Authorization Plugin in a controller without a model, but related with other models?

这对于有更多蛋糕经验的开发者来说应该很容易,但不适合我。

谢谢!!

【问题讨论】:

  • 我投票结束,因为这不是一个问题
  • 你好盐水!您如何建议我将其发布以帮助其他开发人员?这是我的第一篇文章。谢谢!
  • 您将问题作为问题发布,并将答案作为实际答案发布在下面的表格中。如果您至少有 15 点声望,这可以在创建问题时完成,否则您必须在发布问题后稍后回答。见stackoverflow.com/help/self-answer
  • 谢谢!!我会尽量做到这一点:)
  • 请澄清您的具体问题或提供更多详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: php cakephp authorization cakephp-4.x


【解决方案1】:

我终于找到了解决方案! 我将它分享给有同样疑问的人开始使用 Auth 插件。

模型: UsersTable.php
控制器: AccountsController.php

这是一个在数据库中没有实体或表的控制器,但它使用了用户模型。

AccountsController.php

<?PHP
declare(strict_types = 1);

namespace App\Controller;

use Cake\Routing\Router;

class AccountsController extends AppController
{

    public function initialize(): void
    {
        parent::initialize();
        $this->loadModel('Users');
    }

    public function beforeFilter(\Cake\Event\EventInterface $event)
    {
        parent::beforeFilter($event);
        $this->Authentication->addUnauthenticatedActions(['login']);

        // Skip all other methods
        $this->Authorization->skipAuthorization();
    }

    public function editar()
    {
        $user_id = $this->request->getSession()->read('Auth.id');

        // Forcing the method to Auth
        // 1st call the user model
        $usuario = $this->Users->get($user_id);
        // Then, call the auth in the Users Policy
        $this->Authorization->authorize($usuario, 'editar');
    }

用户政策中:

    public function canEditar(IdentityInterface $user, User $resource)
    {
        // logged in users can delete their own articulos.
        return $this->isAuthor($user, $resource);
    }

    protected function isAuthor(IdentityInterface $user, User $resource)
    {
        return $user->id === $user->getIdentifier();
        // This is a simple logic. But others can be created.
    }

仅此而已。您可以在官方 Cake Book (https://book.cakephp.org/authorization/2/en/index.html) 或 MarkStory 博客 (http://mark-story.com/posts/view/introducing-the-cakephp-authorization-plugin) 中找到有关此插件的更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2012-07-06
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多