Zend框架用户身份验证

时间:2009-07-29 13:22:35

标签: zend-framework authentication

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

我有一个网站和一个用Zend Framework编写的 REST 服务器,但没有实现用户会话喷射。

THX!

1 个答案:

答案 0 :(得分: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_authzend_acl上的更多帮助,可以查看此how to