cakephp 安全
安全性是构建 web 应用程序时的另一个重要特性。它向网站用户保证,他们的数据是安全的。 cakephp 提供了一些工具来保护您的应用程序。
加解密
cakephp 中的安全库提供了加密和解密数据的方法。以下是两种方法,用途相同。
static cake\utility\security::encrypt($text, $key, $hmacsalt = null) static cake\utility\security::decrypt($cipher, $key, $hmacsalt = null)
encrypt 方法以 text 和 key 为参数对数据进行加密,返回值为带 hmac 校验和的加密值。
要散列数据,使用 hash() 方法。以下是 hash() 方法的语法。
static cake\utility\security::hash($string, $type = null, $salt = false)
csrf
csrf 代表 跨站请求伪造。通过启用 csrf 组件,您可以抵御攻击。 csrf 是 web 应用程序中的常见漏洞。
它允许攻击者捕获并重放先前的请求,有时还使用其他域上的图像标签或资源提交数据请求。 csrf 可以通过简单地将 csrfcomponent 添加到你的组件数组来启用,如下所示:
public function initialize(): void {
parent::initialize();
$this->loadcomponent('csrf');
}
csrfcomponent 与 formhelper 无缝集成。每次使用 formhelper 创建表单时,它都会插入一个包含 csrf 令牌的隐藏字段。
虽然不推荐这样做,但您可能希望在某些请求上禁用 csrfcomponent。您可以在 beforefilter() 方法期间使用控制器的事件调度器来实现。
public function beforefilter(event $event) {
$this->eventmanager()->off($this->csrf);
}
安全组件
安全组件对您的应用程序应用更严格的安全性。它为各种任务提供方法,例如:
示例
在 config/routes.php 文件中进行更改,如以下程序所示。
config/routes.php
use cake\http\middleware\csrfprotectionmiddleware;
use cake\routing\route\dashedroute;
use cake\routing\routebuilder;
$routes--->setrouteclass(dashedroute::class);
$routes->scope('/', function (routebuilder $builder) {
$builder->registermiddleware('csrf', new csrfprotectionmiddleware([
'httponly' => true,
]));
$builder->applymiddleware('csrf');
//$builder->connect('/pages',
['controller'=>'pages','action'=>'display', 'home']);
$builder->connect('login',['controller'=>'logins','action'=>'index']);
$builder->fallbacks();
});
在 src/controller/loginscontroller.php 中创建一个 loginscontroller.php 文件。 将以下代码复制到控制器文件中。
src/controller/loginscontroller.php
namespace app\controller;
use app\controller\appcontroller;
class loginscontroller extends appcontroller {
public function initialize() : void {
parent::initialize();
$this--->loadcomponent('security');
}
public function index(){
}
}
?>
在 src/template 创建一个 logins 目录,然后在该目录下创建一个名为index.php 的 view 文件。将以下代码复制到该文件中。
src/template/logins/index.php
echo $this--->form->create(null,array('url'=>'/login'));
echo $this->form->control('username');
echo $this->form->control('password');
echo $this->form->button('submit');
echo $this->form->end();
?>
通过访问以下 url 执行上述示例-http://localhost/cakephp4/login
输出
执行后,您将收到以下输出。


