2014-01-10 47 views
0

我在CakePHP 2.4中遇到了一些麻煩。我烘烤了一個簡單的應用程序來創建登錄。我做了本書中的所有內容(Auth和Tutorial)。但只有sha1有效。但不是sha256或md5。在搜索和測試之後,我來到了一個解決方案,我必須更改書中的示例代碼,現在它可以工作。但我認爲,這不是合適的解決方案。僅在sha1中使用CakePHP 2.4進行身份驗證?

我的確在AppController中的以下內容:

App::uses('Controller', 'Controller'); 
    class AppController extends Controller { 
    public $components = array(
     'Session', 
     'Auth' => array(
      'authenticate' => array(
       'Form' => array(
        'passwordHasher' => array(
         'className' => 'Simple', 
         'hashType' => 'sha256' 
        ) 
       ) 
      ) 
     ) 
    ); 
} 

我有MD5,SHA1和SHA256測試這一點。沒問題。如果密碼被適當地散列,登錄就可以工作。

但我注意到,添加一個用戶只適用於sha1,因爲這是默認的散列。 我的用戶模型beforeSafe功能是這樣的(從書):

App::uses('SimplePasswordHasher', 'Controller/Component/Auth'); 
class User extends AppModel { 
    public function beforeSave($options = array()) { 
    if (isset($this->data[$this->alias]['password'])) { 
     $passwordHasher = new SimplePasswordHasher(); 
      $this->data[$this->alias]['password'] = $passwordHasher->hash(
       $this->data[$this->alias]['password'] 
     ); 
    } 
    return true; 
    } 
} 

我想,這在AppController中設置就足夠了,改變SimplePasswordHasher在這方面了。但就目前來看,這還不夠。所以我改成了這樣:

$this->data[$this->alias]['password'] = $passwordHasher->hash(
    $this->data[$this->alias]['password'] 
); 

這個

$this->data[$this->alias]['password'] = Security::hash(
    $this->data[$this->alias]['password'], 
'sha256', 
true 
); 

現在一切就像一個魅力。但我的問題:

1)我是對的,這是必要的,或者是我的代碼有其他錯誤?

2)據我所知$xxx->zzz只適用於控制器和xxx::zzz()爲無處不在,對嗎?

3)爲什麼我必須說安全哈希,它應該再次用sha256散列字符串,當我說已經在AppController中一般?

回答

0

1.據我所知,您的方法是正確的。可能存在一個更清潔的方式,但我使用bcrypt,而食譜說做一些非常相似的事情。

2.你可以像你說的那樣想一個簡單的解釋。基本上->object-operator,用於處理物體例如$this->doEverything。而::scope-resolution-operator,它用於查找Class靜態屬性或方法。通常你可以在任何地方運行,例如Security::hash()

看看here,你應該改變你的AppController到:

'passwordHasher' => array(
       'className' => 'Simple', 
       'hashType' => 'sha256' 
      ) 

,以適應在recomendations。儘管我已經嘗試過了,並沒有將SimplePasswordHasher更改爲SHA256。這是蛋糕似乎無視某種方式的參考。但這是簡單的哈希,旨在簡單的事情,所以你應該做你自己的方法,或一個更適合你的需求。