在我们的CakePHP应用程序中,我们尝试使用Auth组件进行登录。
这是AppController:
class AppController extends Controller {
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'homes', 'action' => 'dashboard'),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'home')
)
);
public function beforeFilter() {
$this->Auth->allow('index','logout','display','home');
}
这是UsersController:
class UsersController extends AppController {
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('add');
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
public function logout() {
$this->redirect($this->Auth->logout());
}
public function index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
}
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('Checkin now'));
$this->redirect(array('action' => 'login'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
}
}
}
然后按照以下步骤操作:
http://localhost/cakephp/
home.ctp
导航至http://localhost/cakephp/users/login
进行登录,使用Login
按钮home.ctp
页面而不是AppController
中提到的页面。第二次尝试:
http://localhost/cakephp/users/login/
AppController
中提到的正确页面。为什么Auth组件表现得像这样......
答案 0 :(得分:0)
检查您的appcontroller,您正在重定向从家到仪表板的登录,它无法将您从用户重定向到登录
改变你的:
app控制器
'loginRedirect' => array('controller' => 'users', 'action' => 'dashboard'),
和usercontroller
public function login() {
if ($this->request->is('post')) {
/* login and redirect to url set in app controller */
if ($this->Auth->login()) {
return $this->redirect(array('controller' => 'users','action' => 'dashboard'));
}
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
答案 1 :(得分:0)
根据documentation,您必须按如下方式更改重定向:
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
// Prior to 2.3 use `return $this->redirect($this->Auth->redirect());`
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
请注意更改return $this->redirect($this->Auth->redirectUrl());