📅  最后修改于: 2020-10-26 05:13:24             🧑  作者: Mango
本章介绍CakePHP中有关身份验证过程的信息。
身份验证是识别正确用户的过程。 CakePHP支持三种身份验证。
FormAuthenticate-它允许您基于表单POST数据对用户进行身份验证。通常,这是用户输入信息的登录表单。这是默认的身份验证方法。
BasicAuthenticate-它允许您使用基本HTTP身份验证来验证用户
DigestAuthenticate-它允许您使用Digest HTTP身份验证来对用户进行身份验证。
如以下代码所示,在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'
]
]);
}
public function beforeFilter(Event $event) {
$this->Auth->allow(['index','view']);
$this->set('loggedIn', $this->Auth->user());
}
}
在src / Controller / AuthexsController.php中创建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.php的View文件。将以下代码复制到该文件中。
src / Template / Authexs / login.php
Form->create();
echo $this->Form->control('username');
echo $this->Form->control('password');
echo $this->Form->button('Submit');
echo $this->Form->end();
?>
创建另一个名为logout.php的View文件。将以下代码复制到该文件中。
src / Template / Authexs / logout.php
You are successfully logged out.
创建另一个名为index.php的View文件。将以下代码复制到该文件中。
src / Template / Authexs / index.php
You are successfully logged in.
Html->link('logout',[
"controller" => "Authexs","action" => "logout"
]);
?>
通过访问以下URL执行以上示例。
http:// localhost / cakephp4 / auth
身份验证已实现,并且一旦您尝试访问上述URL,您将被重定向到登录页面,如下所示。
提供正确的凭据后,您将登录并重定向到如下所示的屏幕。
单击注销链接后,将再次将您重定向到登录屏幕。