Basic認証
HTTPのBasic認証を行うには、SecurityComponentの$loginOptions属性の'type'キーに'basic'を設定し、requireLogin()メソッドで認証の必要なアクションを指定します。ユーザー情報は$loginOptions属性の'users'キーに設定するか$loginUsers属性にセットしておきます。
ログイン用コールバックメソッドを使う
ユーザー数が多い場合などは$loginOptions属性の'login'キーにログイン用コールバックメソッドを指定し、そのメソッドでユーザー認証を行うと便利です。
ユーザー認証部分にAuthコンポーネントを使用してRSS配信の保護にBasic認証を使用した例です。
HTTP basic authentication with users from database
class MyController extends AppController {
var $components = array('Security','RequestHandler');
function beforeFilter() {
if ( $this->RequestHandler->isRss() ) {
$this->Auth->allow('index');//指定アクションでのAuthコンポーネントの認証を外す
$this->Security->loginOptions = array(
'type'=>'basic',
'login'=>'authenticate',
'realm'=>'Protected Area'
);
$this->Security->requireLogin('index');//指定アクションにBasic認証をかける
}
parent::beforeFilter();
}
function authenticate($args) {
// Authコンポーネントの認証を行う。
$data[ $this->Auth->fields['username'] ] = $args['username'];
$data[ $this->Auth->fields['password'] ] = $this->Auth->password($args['password']);
if ($this->Auth->login($data) ) {
return true;
}
$this->Security->blackHole($this, 'login');
return false;
}
function index() {
// Basic認証で保護されたアクション
}
}