CakePHP 2 Basic Auth Authentication
Asked Answered
I

1

5

I am moving from CakePHP 1.3 to CakePHP 2.2.2 and want to use Basic Http authentication for a simple admin area. I am just not able to make it work and I am thinking that I understood something wrong in the documentation.

From the documentation I understood I have to do something like

public $components = array(
    'Auth' => array(
      'authenticate' => array(
        'Basic'
      ),
      'authError' => 'You may not access this area.',
      'authorize' => array('Controller')
    )
  );

I understand that further I need to extend the BaseAuthenticate Component to return valid user date but even with the above configuration I would expect that the browser's Http Access Dialog would open up in a popup window. But nothing like this happens, instead I am redirected to /users/login which does not exist. Why do I need a login view for Http Access? I am confused.

Incapacitate answered 25/9, 2012 at 15:13 Comment(0)
C
8

Add the Auth component to your controller (or to the AppController)

class ThingsController extends AppController {  
    var $components = array('Auth');
}

CakePHP requires a login action, so even if you use Basic authentication, where the HTTP agent is responsible for the UI to collect authentication details, you need to designate an action in some controller which will handle the login (in the Basic case, it will send the WWW-Authenticate: Basic header if the user is not authenticated yet).

You can set the AuthCompoment's $loginAction, but this defaults (and is advisable not to break conventions) to the login method in the UsersController. So, first create an empty template at View/Users/login.ctp, then add the following to your UsersController

class UsersController extends AppController {

    public $components = array(
        'Session',
        'Auth' => array(
            'authenticate' => array('Basic')
        )
    );

    public function login() {
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirect());
        } else {
            $this->Session->setFlash('Not able to login');
        }
    }

    public function logout() {
        $this->redirect($this->Auth->logout());
    }

}
Communard answered 25/9, 2012 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.