4

What is the best practice for user website/REST authentication in ZV MVC? How and where to put the code in the ZF framework? Can you provide me a code example?

I have a website and a REST server written in Zend Framework but no user session jet implemented.

THX!

1
  • Any luck with this? I am in the same situation. Commented Feb 1, 2010 at 13:25

1 Answer 1

1

Authentication is setup in the _initAutoload of the bootstrap file, e.g. like this:

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

In case of a REST authentication you might need to authenticate by just passing the login parameters instead of logging in through a form.

So it might look like this in your 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' );
            } 
       }
   }
}

If you need more help on zend_auth and zend_acl you might have a look at this how to.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.