安全性是構(gòu)建Web應(yīng)用程序的另一個重要特征。它確保了網(wǎng)站用戶數(shù)據(jù)的安全。 CakePHP提供了一些工具,以確保您的應(yīng)用程序安全。
CakePHP的安全類庫提供加密和解密數(shù)據(jù)的方法。以下兩種方法分別用于加密解密數(shù)據(jù)。
static CakeUtilitySecurity::encrypt($text, $key, $hmacSalt = null) static CakeUtilitySecurity::decrypt($cipher, $key, $hmacSalt = null)
加密方法將文本和鍵作為參數(shù)來加密數(shù)據(jù),返回HMAC校驗值。
hash()方法用來散列數(shù)據(jù)。以下是hash()方法的語法。
static CakeUtilitySecurity::hash($string, $type = NULL, $salt = false)
CSRF代表跨站請求偽造 。通過啟用CSRF組件,就可以得到反攻擊保護。 CSRF是Web應(yīng)用程序的常見漏洞。它允許攻擊者捕獲和重放前一個請求,在其他域使用圖像標(biāo)記或資源提交數(shù)據(jù)請求。CSRF只需通過簡單的添加CsrfComponent至組件陣列即可啟用。
public function initialize(){ parent::initialize(); $this->loadComponent('Csrf'); }
該CsrfComponent與表單助手無縫集成。每次通過表單助手創(chuàng)建表單的時候,它都會插入包含CSRF安全令的隱藏域。
雖然不建議這樣做,你可能要在某些請求中禁用CsrfComponent。您可以通過使用控制器的事件調(diào)度程序在beforeFilter()方法運行的過程中這樣做。
public function beforeFilter(Event $event){ $this->eventManager()->off($this->Csrf); }
安全組件適用于安全要求更嚴(yán)格的應(yīng)用程序。它為各類任務(wù)提供方法,如:-
限制您的應(yīng)用程序接受的http方法 。在反作用發(fā)生之前,您應(yīng)該總是檢查HTTP方法。您應(yīng)該檢查HTTP方法或使用Cake\Network\Request::allowMethod()以確保使用正確的HTTP方法。
表單篡改保護 -默認(rèn)情況下,SecurityComponent阻止用戶以特定的方式篡改表單。SecurityComponent將阻止以下事件 -
未知域不能被添加到表單。
字段不能從表單中刪除。
隱藏域的值不能被修改。
要求使用SSL -所有動作要求SSL加密。
限制跨控制器的通信 -我們可以限制哪些控制器可將請求發(fā)送到此控制器。我們也可以限制哪些方法可以發(fā)送請求到此控制器的方法。
修改config/routes.php文件如下。
config/routes.php文件
<?php use CakeCorePlugin; use CakeRoutingRouteBuilder; use CakeRoutingRouter; Router::defaultRouteClass('DashedRoute'); Router::scope('/', function (RouteBuilder $routes) { $routes->connect('login',['controller'=>'Logins','action'=>'index']); $routes->fallbacks('DashedRoute'); }); Plugin::routes();
在src/Controller/目錄下創(chuàng)建一個LoginsController.php文件。復(fù)制以下代碼至其中。
src/Controller/LoginsController.php
<?php namespace AppController; use AppControllerAppController; class LoginsController extends AppController{ public function initialize(){ parent::initialize(); $this->loadComponent('Security'); } public function index(){ } } ?>
在src/Template目錄下創(chuàng)建一個Logins目錄,并在該Logins目錄下創(chuàng)建一個名為index.ctp的視圖文件。復(fù)制以下代碼至其中。
src/Template/Logins/index.ctp
<?php echo $this->Form->create("Logins",array('url'=>'/login')); echo $this->Form->input('username'); echo $this->Form->input('password'); echo $this->Form->button('Submit'); echo $this->Form->end(); ?>
通過訪問以下網(wǎng)址執(zhí)行上面的例子- http://localhost:85/CakePHP/login
執(zhí)行以上程序,您會看到如下頁面:
更多建議: