// in a controller beforeFilter or initialize // Make view and index not require a logged in user.
$this->Authentication->allowUnauthenticated(['view', 'index']);
<?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);
}
}
2条答案
按热度按时间cbwuti441#
您可能指的是身份验证而不是授权。无论如何,从文档中:
默认情况下,组件的所有操作都需要经过身份验证的用户。您可以使用allowUnauthenticated()在特定的控制器中禁用此行为:
更多信息:The Authentication plugin in the Cake Book。
snz8szmq2#
我认为你做的方式不对。为了授权,你必须写一个请求策略。每当你bake控制器的时候,只要添加--前缀Admin或者任何你想要的。
将所有管理控制器放在一个位置。在路由文件中添加路由
`请求策略。创建一个角色表,并在Users表中添加role_id列,其余的部分您将通过下面的代码来理解。
`
然后实现应用程序的AuthorizationServiceProviderInterface