2009-07-29 88 views
4

ZV MVC中用户网站/ REST身份验证的最佳做法是什么?如何和在哪里把代码在ZF框架?你能给我一个代码示例吗?Zend Framework用户身份验证

我有一个网站并写入Zend框架一个REST服务器,但没有实施用户会话飞机。

THX!

+0

对此有何好运?我处于同样的情况。 – 2010-02-01 13:25:35

回答

1

认证在引导文件的_initAutoload中设置,例如,像这样:

if(Zend_Auth::getInstance()->hasIdentity()) { 
    Zend_Registry::set('role', Zend_Auth::getInstance() 
         ->getStorage()->read()->role); 
}else{ 
    Zend_Registry::set('role', 'guests'); 
} 

在您可能需要刚好路过登录参数,而不是通过表单登录来验证REST认证的情况下。

因此,它可能看起来像这样在你的AuthenticationController

private function getAuthAdapter() { 
    $authAdapter = new Zend_Auth_Adapter_DbTable(
         Zend_Db_Table::getDefaultAdapter()); 
    $authAdapter->setTableName('users') // the db table where users are stored 
       ->setIdentityColumn('email')      
       ->setCredentialColumn('password') 
       ->setCredentialTreatment('SHA1(CONCAT(?,salt))'); 

    return $authAdapter; 
} 

public function logoutAction() { 
    Zend_Auth::getInstance()->clearIdentity(); 
    $this->_redirect('index/index'); 
} 

public function loginAction(){ 
    if (Zend_Auth::getInstance()->hasIdentity()){ 
     $this->_redirect('index/index'); 
    } 
    if ($request->isPost()){ 
     $username = $request->getPost('username'); 
     $password = $request->getPost('password'); 

     if ($username != "" && $password != "") { 
      $authAdapter = $this->getAuthAdapter(); 
      $authAdapter->setIdentity($username) 
         ->setCredential($password); 
      $auth = Zend_Auth::getInstance(); 
      $result = $auth->authenticate($authAdapter); 

      if($result->isValid()){ 
       $identity = $authAdapter->getResultRowObject(); 
       $authStorage = $auth->getStorage(); 
       $authStorage->write($identity); 
       $this->_redirect ('index/index'); 
      } 
     } 
    } 
} 

如果您需要zend_auth更多的帮助和zend_acl你可能有一个看看这个how to