How to use multiple Auth components?

前端 未结 1 360
栀梦
栀梦 2021-01-22 19:35

I configure a Auth component to \"Admin page\", using the users model. But now, I also want create/configure a Auth to the clients. I try \"rewrite\" the inialize()



        
相关标签:
1条回答
  • 2021-01-22 19:55

    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

    • Cookbook > Controllers > Components > Authentication > Configuration options
    • Cookbook > Controllers > Components > Aliasing Components
    0 讨论(0)
提交回复
热议问题