-1

在我们的 CakePHP 应用程序中,我们尝试使用 Auth 组件进行登录。

这是应用控制器:

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');
    }

这是用户控制器:

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.'));
            }
        }
    }
}

然后按照以下步骤操作:

  1. 在浏览器中输入的 URL 为http://localhost/cakephp/
  2. 从 Homepage home.ctp,导航到http://localhost/cakephp/users/login登录,使用Login按钮
  3. 输入用户名和密码,然后点击登录按钮
  4. 然后它重定向到上一个访问home.ctp的页面,而不是AppController.

第二次尝试:

  1. 参观过http://localhost/cakephp/users/login/直接从 URL 字段
  2. 然后输入登录凭据,然后它重定向到正确的页面,如AppController.

为什么 Auth 组件的行为是这样的.....

4

2 回答 2

0

检查您的应用程序控制器,您正在将登录从主页重定向到仪表板,它无法将您从用户重定向到登录

改变你的:

应用控制器

        'loginRedirect' => array('controller' => 'users', 'action' => 'dashboard'),

和用户控制器

   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'));

    }

}
于 2013-09-13T05:54:30.217 回答
0

根据文档,您必须按如下方式更改重定向:

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());

于 2013-09-13T06:18:04.430 回答