如何在cakePHP4中禁用授权中间件?

gpnt7bae  于 2022-11-11  发布在  PHP
关注(0)|答案(2)|浏览(123)

默认情况下,授权插件应用于全局范围。对于一些我不想应用任何授权的控制器。我不得不为每个操作手动使用skipAuthorization配置。对于身份验证插件,我只能为每个需要身份验证的控制器加载身份验证组件。但是,即使我没有在控制器中加载授权组件,授权中间件似乎也会一直工作。2那么,这是为什么呢?3有没有办法可以禁用整个控制器的授权过程?

cbwuti44

cbwuti441#

您可能指的是身份验证而不是授权。无论如何,从文档中:

// in src/Controller/AppController.php
public function initialize()
{
    parent::initialize();

    $this->loadComponent('Authentication.Authentication');
}

默认情况下,组件的所有操作都需要经过身份验证的用户。您可以使用allowUnauthenticated()在特定的控制器中禁用此行为:

// in a controller beforeFilter or initialize // Make view and index not require a logged in user.
$this->Authentication->allowUnauthenticated(['view', 'index']);

更多信息:The Authentication plugin in the Cake Book

snz8szmq

snz8szmq2#

我认为你做的方式不对。为了授权,你必须写一个请求策略。每当你bake控制器的时候,只要添加--前缀Admin或者任何你想要的。

cake bake controller Users --prefix Admin

将所有管理控制器放在一个位置。在路由文件中添加路由

$builder->prefix('Admin',['_namePrefix' => 'admin:'], function (RouteBuilder $builder) {
    $builder->connect('/', ['controller' => 'Users', 'action' => 'Index']);
    $builder->fallbacks(DashedRoute::class);
});

`请求策略。创建一个角色表,并在Users表中添加role_id列,其余的部分您将通过下面的代码来理解。

<?php 
namespace App\Policy;

use Authorization\IdentityInterface;
use Authorization\Policy\RequestPolicyInterface;
use Cake\Http\ServerRequest;
class RequestPolicy implements RequestPolicyInterface
{
    /**
     * Method to check if the request can be accessed
     *
     * @param IdentityInterface|null Identity
     * @param ServerRequest $request Server Request
     * @return bool
     */
    public function canAccess($identity, ServerRequest $request)
    {
        $role = 0;
        if(!empty($identity)){
            $data = $identity->getOriginalData();
            $role = $data['role_id'];
        } 
         if(!empty($request->getParam('prefix'))){
            switch($request->getParam('prefix')){
                        case 'User' : return (bool)($role === 3);
                        case 'Admin': return (bool)($role === 1) || (bool)($role === 2);

            }

         }else{
             return true;
         }

        return false;

    }
}

`
然后实现应用程序的AuthorizationServiceProviderInterface

use App\Policy\RequestPolicy;
use Authorization\AuthorizationServiceProviderInterface;
use Authorization\AuthorizationService;
use Authorization\Policy\MapResolver;
use Cake\Http\ServerRequest;
use Psr\Http\Message\ServerRequestInterface;

class Application extends BaseApplication implements AuthorizationServiceProviderInterface{
public function getAuthorizationService(ServerRequestInterface $request): AuthorizationServiceInterface
    {
        $mapResolver = new MapResolver();
        $mapResolver->map(ServerRequest::class, RequestPolicy::class);
        return new AuthorizationService($mapResolver);
    }
}

相关问题