我目前正在使用CakePHP 2.4.5并尝试实施授权。我的AppController.php是:
class AppController extends Controller {
public $helpers = array('Html', 'Form', 'Session');
public $components = array(
'Session',
'RequestHandler',
'Auth' => array(
'loginRedirect' => array(
'controller' => 'themeroles',
'action' => 'add'
),
'logoutRedirect' => array(
'controller' => 'pages',
'action' => 'display',
'home'
)
)
);
public function isAuthorized($user) {
$auth = CakeSession::read('Auth');
if (isset($auth['User'])){
$loggedInUser = $auth['User']['username'];
$loggedInRole = $auth['User']['role'];
// Admin can access every action
if (isset($loggedInRole) && $loggedInRole === 'admin') {
return true;
}
if (isset($loggedInUser) &&!empty($user) && $loggedInUser === $user) {
return true;
}
}
CakeSession::write('redirectURL', Router::reverse($this->request, true));
// Default deny
return false;
}
public function beforeFilter() {
$this->Auth->allow('index', 'view');
}
}
我的UsersController有:
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
但重定向后,似乎会话被杀死了。我自动被重定向到登录页面。
我发现可以在core.php中设置解决方案:
Configure::write('Security.level', 'low');
Configure::write('Security.cookie', 'cakephpfdebackend');
Configure::write('Session.cookieTimeout', 0);
Configure::write('Session.checkAgent', false);
Configure::write('Session.cookie_secure',false);
Configure::write('Session.referer_check' ,false);
Configure::write('Session.defaults', 'php');
但这没有用。我错过了什么?
答案 0 :(得分:0)
我认为问题出在你的isAuthorized()
函数上。在每次尝试登录时编写新会话之前,它会发现isset($auth['User'])
已设置但为空。因此,if
都不会运行。结果它返回false。
所以,试试:
if (!empty($auth['User'])){