CakePHP 1.2 has HTTP basic authentication added to Security component which can be added to the controller using the following line in code in the following line of code
var $components = array('Security',);
To use the HTTP basic authentication you should add those lines to the action you want to restrict access:
$this->Security->options = array('type' => 'basic', 'realm' => 'Restricted Area');
$this->Security->loginUsers = array('user1' => 'password1', 'user2' => 'password2');
$this->Security->requireLogin();
Realm option can be any description to the area where you want restriction. This can be any string you want. The option for ‘loginUsers’ is an array which the keys are user names and values are passwords.
To make it more clear, we will use the following code to restrict access to actions that has admin prefix, admin_index for example, this will be used to create authentication over all controllers, so we will need to add it in AppController beforeFilter method to guarantee it will be used in all actions.
class AppController extends Controller{
var $components = array('Security');
function beforeFilter(){
parent::beforeFilter();
if (!empty($this->params['prefix']) &&
$this->params['prefix'] == Configure::read('Routing.admin')){
$this->Security->options = array('type' => 'basic', 'realm' => 'Admin Area');
$this->Security->loginUsers = array('admin' => 'adm1n');
$this->Security->requireLogin();
}
}
}
Exactly what I was looking for, thanks!
To get this to work in CakePHP 1.3, a couple of changes were required:
class AppController extends Controller { var $components = array('Security'); function beforeFilter() { parent::beforeFilter(); if (!empty($this->params['prefix']) && in_array($this->params['prefix'], Configure::read('Routing.prefixes'))) { $this->Security->loginOptions = array('type' => 'basic', 'realm' => 'Admin Area'); $this->Security->loginUsers = array('admin' => 'password', 'user2' => 'password2'); $this->Security->requireLogin(); } } }Hi, thanks for this post. It is exactly what i was looking for. Look forward to reading more tips!
Selena,
Webmaster at Cellulean