How to use multiple Auth components?

和自甴很熟 提交于 2019-12-02 02:41:12

Reconfigure

You don't necessarily need to use multiple auth component instances, you can simply reconfigure it in the extended controller, using the components config() method, something along the lines of:

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
    );
}

Note the use of the storage option, you should define a different key here (the default is Auth.User), otherwise an authenticated client might be able to access the admin area and vice versa, as the user data would get stored in the same session key!

Use aliasing

You could use multiple auth components if required, to do so you'd have to use aliasing, so that the components don't try to override each other:

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

Don't forget to use a different session key in this case too!

You'd access that component instance as $this->ClientAuth accordingly, and you may have to allow access to the login() method via $this->Auth, ie. in ClientsController::initialize() or beforeFilter() do:

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

There might be further side-effects, so be careful.

See also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!