身份验证
身份验证是识别正确用户的过程. CakePHP支持三种类型的身份验证.
FormAuthenticate : 它允许您根据表单POST数据对用户进行身份验证.通常这是用户输入信息的登录表单.这是默认的身份验证方法.
BasicAuthenticate : 它允许您使用基本HTTP身份验证对用户进行身份验证.
DigestAuthenticate : 它允许您使用摘要HTTP身份验证对用户进行身份验证.
FormAuthentication示例
进行更改在config/routes.php文件中,如下面的代码所示.
config/routes.php
connect('/auth',['controller'=>'Authexs','action'=>'index']); $routes->connect('/login',['controller'=>'Authexs','action'=>'login']); $routes->connect('/logout',['controller'=>'Authexs','action'=>'logout']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
更改AppController.php文件的代码,如以下程序所示.
src/Controller/AppController.php
loadComponent('RequestHandler'); $this->loadComponent('Flash'); $this->loadComponent('Auth', [ 'authenticate' => [ 'Form' => [ 'fields' => ['username' => 'username', 'password' => 'password'] ] ], 'loginAction' => ['controller' => 'Authexs', 'action' => 'login'], 'loginRedirect' => ['controller' => 'Authexs', 'action' => 'index'], 'logoutRedirect' => ['controller' => 'Authexs', 'action' => 'login'] ]); $this->Auth->config('authenticate', [ AuthComponent::ALL => ['userModel' => 'users'], 'Form']); } public function beforeRender(Event $event){ if (!array_key_exists('_serialize', $this=>viewVars) && in_array($this->response=>type(), ['application/json', 'application/xml'])) { $this->set('_serialize', true); } } }
在 src创建 AuthexsController.php 文件/Controller/AuthexsController.php 的.将以下代码复制到控制器文件中.
src/Controller/AuthexsController.php
request->is('post')){ $user = $this->Auth->identify(); if($user){ $this->Auth->setUser($user); return $this->redirect($this->Auth->redirectUrl()); } else $this->Flash->error('Your username or password is incorrect.'); } } public function logout(){ return $this->redirect($this->Auth->logout()); } }?>
在 src/Template 创建目录 Authexs 并在该目录下创建视图名为 login.ctp 的文件.将以下代码复制到该文件中.
src/Template/Authexs/login.ctp
Form->create(); echo $this->Form->input('username'); echo $this->Form->input('password'); echo $this->Form->button('Submit'); echo $this->Form->end();?>
创建另一个名为 logout.ctp 的查看文件.将以下代码复制到该文件中.
src/Template/Authexs/logout.ctp
You are successfully loggedout.
创建另一个名为 index.ctp 的查看文件.将以下代码复制到该文件中.
src/Template/Authexs/index.ctp
You are successfully logged in. Html->link('logout',["controller" => "Authexs","action" => "logout"]); ?>
访问以下网址执行上述示例.
http://localhost:85/CakePHP/auth
输出
由于身份验证已经实施,因此一旦您尝试访问上述URL,您将被重定向到登录页面,如下所示.
提供后正确的凭据,您将登录并重定向到屏幕,如下所示.
点击注销链接后,您将再次被重定向到登录屏幕.