重定向所有网页下的webroot登录页在Cakephp


Redirect all webpages under webroot to login page in Cakephp

我使用的是cakephp 2.4.5。我想重定向所有用户谁还没有登录到登录页面。我基本上是按照这里的说明做的。

总之,重要的部分是以下AppController.php 的代码
public $components = array('Session',
                            'Auth' => array(
                                'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
                                'logoutRedirect' => array('controller' => 'users', 'action' => 'login'),
                                'authError' => 'You must be logged in to view this page.',
                                'loginError' => 'Invalid Username or Password entered, please try again.'        
                            ));

任何使用此URL格式http://localhost/cakephp245/controllers/XXX的网站将被重定向到登录页面。但是,位于app/webroot内的URL看起来像http://localhost/cakephp245/app/webroot/XXX的网站将不会被重定向到登录页面。

我怎么能强迫位于app/webroot文件夹内的网站被重定向到登录页面?

以下是可以帮助解决问题的步骤:-

1)阅读如何在appController中加载授权组件的文档https://book.cakephp.org/3.0/en/controllers/components/authentication.html
代码应该像下面的代码

$this->loadComponent('Auth', [
                'loginAction' => [
                    'controller' => 'Users',
                    'action' => 'login',
                    'plugin' => null
                ],
                //'authorize' => ['Controller'],
                'loginRedirect' => [
                    'controller' => 'Users',
                    'action' => 'dashboard'
                ],
                'logoutRedirect' => [
                    'controller' => 'Users',
                    'action' => 'login',
                ],
                'authenticate' => [
                    'Form' => [
                        'fields' => ['username' => 'email', 'password' => 'password']
                    ]
                ],
                'unauthorizedRedirect' => false,
                'authError' => 'Did you really think you are allowed to see that?',
                'storage' => 'Session'
            ]);

2)添加以下代码到usersController

的beforeFilter()
$this->Auth->allow(['login','logout','register']);  // these function will be pulic access

3)这里是登录功能,把它放在UserController

 public function login()
    {
        $this->viewBuilder()->layout('adminlogin'); // set the admin login layout 
        $user = $this->Users->newEntity();
        $this->set('user', $user);
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user){
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }else{
                $this->Flash->error(__('Invalid username or password, try again'));         
            }
        }
    }

将此函数添加到AppController

public function beforeFilter() {        
    $this->Auth->deny();        
    $this->Auth->allow('login');
}

这样,在登录之前唯一允许的操作是登录本身。不过,这不会使图像或脚本或css不可用,如果这是你的目标。

虽然我不完全确定,但我相信没有办法拒绝别人访问这种类型的资源。