在应用中,只想简单实现认证过程,不想用ACL,网上有好多实现方法如前面文章视频http://blog.youkuaiyun.com/lap2004/article/details/7871357 也可以看看纯通过session实现认证http://www.phpgz.com/html/framework/kcakephp/20090724/764.html 在看了书 CakePHP Web Application Development 后,通过变量logedin控制 较为简单,具体过程如下:
1.设置Anth各参数
class AppController extends Controller {
public $components = array(
'Auth' => array('authorize' => 'Controller'),//为控制器认证
);
function beforeFilter() {
$this->Auth->allow(); //允许所有操作 2.0之前为allow('*');
$this->Auth->fields = array('username' => 'username', 'password' => 'password');
$this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
$this->Auth->loginRedirect = array('controller' => 'articles', 'action' => 'index');
$this->Auth->logoutRedirect = '/';
$this->Auth->loginError = 'Invalid e-mail / password combination. Please try again';
$this->Auth->AuthError="anth error";
$this->set('logedin',$this->Auth->user('id'));//变量logedin在各想限制访问view页面 控制是否显示内容,如通过认证$this->Auth->user('id'))有值非空 ,未通过为空
}
public function isAuthorized($user = null) {
return true; //只要用户通过认证,都授权
}
2。users控制器中 $this->Auth->login() $this->Auth->logout() 必须在函数中手动调用,2.0之前自动调用
public function admin_logout() {
$this->redirect($this->Auth->logout());
}
public function admin_login(){
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
3.VIEW视图中想限制访问页面加if语句
<?php if ($logedin) { ?>
开放限制访问内容
<?php } else { ?>
提示登录后再访问内容
<?php }; ?>
4.在user模型中在数据保存前要对密码进行加密(2.0之前自动加密) 2.0后登录时框架自动加密
<?php
App::uses('AppModel', 'Model');
class User extends AppModel {
public function beforeSave($options = array()) {
$this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
return true;
}
}
5.登录 注册 等为users控制器,而限制访问页面重点在另一控制器如articles控制器,涉及调用另为控制器链接,可用直接用绝对地址
<?php echo $this->Html->link(__('登录'), '../users/login'); ?>