Phalcon - 安全特性



Phalcon 透過安全元件提供安全特性,該元件有助於執行某些任務,例如密碼雜湊和**跨站點請求偽造**(CSRF)。

雜湊密碼

**雜湊**可以定義為將固定長度的位元串轉換為指定長度的過程,以使其無法逆轉。輸入字串的任何更改都會更改雜湊資料的取值。

雜湊資料的解密透過將使用者輸入的值作為輸入並將其與相同的雜湊形式進行比較來完成。通常對於任何基於 Web 的應用程式,將密碼以純文字形式儲存都是一種不好的做法。它容易受到第三方攻擊,因為那些訪問資料庫的人可以輕鬆獲取任何使用者的密碼。

Phalcon 提供了一種簡單的方法來以加密形式儲存密碼,遵循諸如**md5、base64**或**sh1**之類的演算法。

如前幾章所述,我們在其中為部落格建立了一個專案。登入螢幕接受使用者名稱和密碼作為使用者的輸入。為了接收來自使用者的密碼並將其解密為特定形式,使用了以下程式碼片段。

然後將解密的密碼與從使用者接收的輸入密碼進行匹配。如果值匹配,則使用者可以成功登入到 Web 應用程式,否則將顯示錯誤訊息。

<?php  
class UsersController extends Phalcon\Mvc\Controller {  
   public function indexAction() {  
   }  
   public function registerUser() { 
      $user = new Users();  
      $login    = $this->request->getPost("login"); 
      $password = $this->request->getPost("password");
      $user->login = $login;  
      
      // Store the hashed pasword 
      $user->password = $this->security->sh1($password);  
      $user->save(); 
   }  
   public function loginAction() {  
      if ($this->request->isPost()) {  
         $user = Users::findFirst(array( 
            'login = :login: and password = :password:', 
            'bind' => array( 
               'login' => $this->request->getPost("login"), 
               'password' => sha1($this->request->getPost("password")) 
            ) 
         ));  
         if ($user === false) { 
            $this->flash->error("Incorrect credentials"); 
            return $this->dispatcher->forward(array( 
               'controller' => 'users', 
               'action' => 'index' 
            )); 
         }
         $this->session->set('auth', $user->id);  
         $this->flash->success("You've been successfully logged in"); 
      }  
      return $this->dispatcher->forward(array( 
         'controller' => 'posts', 
         'action' => 'index' 
      )); 
   }  
   public function logoutAction() { 
      $this->session->remove('auth'); 
      return $this->dispatcher->forward(array( 
         'controller' => 'posts', 
         'action' => 'index' 
      )); 
   }  
}     

儲存在資料庫中的密碼採用**sh1**演算法的加密格式。

Password

一旦使用者輸入了合適的使用者名稱和密碼,使用者就可以訪問系統,否則會顯示錯誤訊息作為驗證。

Validation

跨站點請求偽造 (CSRF)

這是一種攻擊,它迫使 Web 應用程式的已認證使用者執行某些不希望的操作。接受使用者輸入的表單容易受到此攻擊。Phalcon 試圖透過保護透過表單傳送到應用程式外部的資料來防止此攻擊。

每個表單中的資料都透過令牌生成來保護。生成的令牌是隨機的,並且與我們將表單資料傳送到的令牌匹配(大多數情況下透過 POST 方法傳送到 Web 應用程式外部)。

程式碼

<?php echo Tag::form('session/login') ?>  
   <!-- Login and password inputs ... -->  
   <input type = "hidden" name = "<?php echo $this->security->getTokenKey() ?>" 
      value = "<?php echo $this->security->getToken() ?>"/>  
</form> 

**注意** - 在傳送表單令牌時使用會話介面卡很重要,因為所有資料都將儲存在會話中。

使用以下程式碼在**services.php**中包含會話介面卡。

/** 
   * Start the session the first time some component request the session service 
*/ 

$di->setShared('session', function () { 
   $session = new SessionAdapter(); 
   $session->start();  
   return $session; 
});
廣告

© . All rights reserved.