如何使用多个Auth组件?

时间:2016-02-22 14:14:22

标签: php authentication cakephp cakephp-3.0

我使用用户模型将Auth组件配置到"管理员页面"。但现在,我还想为客户创建/配置Auth。我试着"重写" inialize()

//This is in my ClientsController.php
public function initialize()
{
    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
        'authenticate' => [
            'Form' => [
                'userModel' => 'clients',
                'fields' => ['username' => 'client_email', 'password' => 'client_password']
            ]
        ],
        'loginRedirect' => [
            'controller' => 'Clients',
            'action' => 'index'
        ],
        'logoutRedirect' => [
            'controller' => 'Clients',
            'action' => 'login'
        ],
    ]);
}

有了这个,我收到这个日志(如果使用parent :: initalize()收到相同的)

[RuntimeException] The "Auth" alias has already been loaded with the following config: array (...

我不想创建一个" Auth" manualy。如何使用更多的Auth?

...谢谢

1 个答案:

答案 0 :(得分:2)

重新配置

您不一定需要使用多个身份验证组件实例,您只需使用组件config()方法在扩展控制器中重新配置它,就像这样:

public function initialize()
{
    parent::initialize();

    // ...

    $this->Auth->config(
        [
            'authenticate' => [
                'Form' => [
                    'userModel' => 'clients',
                    'fields' => [
                        'username' => 'client_email',
                        'password' => 'client_password'
                    ]
                ]
            ],
            'loginRedirect' => [
                'controller' => 'Clients',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Clients',
                'action' => 'login'
            ],
            'storage' => [
                'className' => 'Session',
                'key' => 'Auth.Client'
            ]
        ],
        null,
        false
    );
}

请注意使用storage选项,您应在此处定义不同的密钥(默认为Auth.User),否则经过身份验证的客户端可能会访问管理区域,反之亦然,因为用户数据将存储在同一个会话密钥中!

使用别名

如果需要,您可以使用多个身份验证组件,这样您就必须使用别名,这样组件就不会试图互相覆盖:

$this->loadComponent('ClientAuth', [
    'className' => 'Auth',
    // ....
]);

在这种情况下,不要忘记使用其他会话密钥!

您相应地将该组件实例作为$this->ClientAuth访问,并且您可能必须允许通过login()访问$this->Auth方法,即。在ClientsController::initialize()beforeFilter()中执行:

$this->Auth->allow('login');

可能还有其他副作用,所以要小心。

另见