2015-09-28 27 views
0

今天我想使用Cakephp3 auth组件。Cakephp3 Auth - 允许一些控制器在没有授权的情况下工作

我有研究cakephp3博客教程和身份验证文档。

我遵循博客教程,现在来看一切工作正常,如登录,注销等..

我想有UsersController被保护,只有使用的时候我会登录。

这是好的,但现在我看到我需要登录到其他控制器的行动,例如我有PagesController,应该是公开的。

我发现这个在文档:

// Allow only the view and index actions. 
$this->Auth->allow(['view', 'index']); 

但我有很多的动作,并在此功能列出的行动可能是有问题的。

我的问题是:我如何全局设置UsersController的所有操作被保护,其余的控制器将被公开?

谢谢。

+0

首先,您应该确保您使用的是正确的条款。授权似乎不同于“_protected并且仅在我登录时才使用”,这听起来更像是Authentication。 – ndm

回答

0

在您的appsController中,您可以添加下面的代码。您必须在$this->Auth->allow('ViewName')中添加所有视图名称。

public function beforeFilter(Event $event) 
{ 
    parent::beforeFilter($event); 
    // Allow users to register and logout. 
    // You should not add the "login" action to allow list. Doing so would 
    // cause problems with normal functioning of AuthComponent. 
    $this->Auth->allow(['Index', 'View', 'Edit', 'CustomViewName']); // NOTE: DO NOT ADD VIEWS THAT ARE USED BY YOUR USERSCONTROLLER. 
} 

并且从UsersController中,您可以删除$this->Auth->allow(['add', 'logout']);。这是我的方式。

1

我想你可以使用ControllerAuthorize.It将允许你在控制器回调中处理授权检查。在你的应用程序组件中添加这个设置。

$this->loadComponent('Auth', [ 
      'authorize' => 'Controller', 
]); 

然后,您可以阻止或允许isAuthorized()

例如访问:

public function isAuthorized($user) { 
     if (isset($user['role']) == 'yourRole') { 
       return TRUE; 
     } 

     else { 
      header("location: Router::url('/', true)"); 
      exit(); 
     } 
} 

详情 cake doc

4

对于UsersController

class UsersController extends AppController 
{ 
    public function beforeFilter(Event $event) 
    { 
     // allow only login, forgotpassword 
     $this->Auth->allow(['login', 'forgotpassword']); 
    } 
} 

用于其他控制器。 (实施例:PagesController)

class PagesController extends AppController 
{ 
    public function beforeFilter(Event $event) 
    { 
     // allow all action 
     $this->Auth->allow(); 
    } 
} 
+0

这是该死的权利。我正在尝试它作为$ this-> Auth-> allow('*'),并想知道为什么它不起作用。刚刚删除'*',它的工作!谢谢! (忽略*两边的空格) –

1

尝试: $这 - > Auth->否认([ '控制器要授权名称']);

0
public function beforeFilter(Event $event){ 
parent::beforeFilter($event); 
$this->Auth->allow(['search']); // NOTE: DO NOT ADD VIEWS THAT ARE USED BY YOUR USERSCONTROLLER.} 

它对我很好。

相关问题