cakephp 安全
安全性是構(gòu)建 web 應(yīng)用程序時的另一個重要特性。它向網(wǎng)站用戶保證,他們的數(shù)據(jù)是安全的。 cakephp 提供了一些工具來保護您的應(yīng)用程序。
加解密
cakephp 中的安全庫提供了加密和解密數(shù)據(jù)的方法。以下是兩種方法,用途相同。
static cake\utility\security::encrypt($text, $key, $hmacsalt = null) static cake\utility\security::decrypt($cipher, $key, $hmacsalt = null)
encrypt 方法以 text 和 key 為參數(shù)對數(shù)據(jù)進行加密,返回值為帶 hmac 校驗和的加密值。
要散列數(shù)據(jù),使用 hash() 方法。以下是 hash() 方法的語法。
static cake\utility\security::hash($string, $type = null, $salt = false)
csrf
csrf 代表 跨站請求偽造。通過啟用 csrf 組件,您可以抵御攻擊。 csrf 是 web 應(yīng)用程序中的常見漏洞。
它允許攻擊者捕獲并重放先前的請求,有時還使用其他域上的圖像標簽或資源提交數(shù)據(jù)請求。 csrf 可以通過簡單地將 csrfcomponent 添加到你的組件數(shù)組來啟用,如下所示:
public function initialize(): void { parent::initialize(); $this->loadcomponent('csrf'); }
csrfcomponent 與 formhelper 無縫集成。每次使用 formhelper 創(chuàng)建表單時,它都會插入一個包含 csrf 令牌的隱藏字段。
雖然不推薦這樣做,但您可能希望在某些請求上禁用 csrfcomponent。您可以在 beforefilter() 方法期間使用控制器的事件調(diào)度器來實現(xiàn)。
public function beforefilter(event $event) { $this->eventmanager()->off($this->csrf); }
安全組件
安全組件對您的應(yīng)用程序應(yīng)用更嚴格的安全性。它為各種任務(wù)提供方法,例如:
示例
在 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 中創(chuàng)建一個 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 創(chuàng)建一個 logins 目錄,然后在該目錄下創(chuàng)建一個名為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 執(zhí)行上述示例-http://localhost/cakephp4/login
輸出
執(zhí)行后,您將收到以下輸出。
