Phalcon - 安全功能


Phalcon 在安全组件的帮助下提供安全功能,该组件有助于执行某些任务,例如密码散列和跨站点请求伪造(CSRF)。

散列密码

散列可以定义为将固定长度的位串以不可逆的方式转换为指定长度的过程。输入字符串的任何更改都会更改哈希数据的值。

哈希数据的解密是通过将用户输入的值作为输入并比较该值的哈希形式来进行的。通常对于任何基于 Web 的应用程序,将密码存储为纯文本是一种不好的做法。它很容易受到第三方攻击,因为有权访问数据库的人可以轻松获取任何用户的密码。

Phalcon 提供了一种以加密形式存储密码的简单方法,该方法遵循md5、base64sh1等算法。

如前面的章节所示,我们创建了一个博客项目。登录屏幕接受用户的用户名和密码输入。要从用户接收密码并以特定形式对其进行解密,请使用以下代码片段。

然后将解密的密码与作为用户输入接受的密码进行匹配。如果该值匹配,则用户可以成功登录到 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算法的加密格式。

密码

一旦用户输入适当的用户名和密码,用户就可以访问系统,否则将显示一条错误消息作为验证。

验证

跨站请求伪造 (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; 
});