Simple Authentication using Zend Framework 2

Jun 9, 2013   //   by kdecom   //   zend framewok 2, ZEND FRAMEWORK, zend framework tutorial, zf2  //  1 Comment

Simple Authentication using Zend Framework 2

It’s always to hard to make a login to work in any framework.  Atleast for me in Zend Frameowork 1 login using auth adapter was quite simple.

$loginData = $form->getData();

$dbAdapter = $this->serviceLocator->get('Zend\Db\Adapter\Adapter');

$authAdapter = new DbTable($dbAdapter, 'user', 'username', 'password', 'MD5(?)');
$authService = $this->serviceLocator->get('auth_service');
$result = $authService->authenticate();
if ($result->isValid()) {
    // set id as identifier in session
    $userId = $authAdapter->getResultRowObject('id')->id;
    return $this->redirect()->toUrl('/main');

} else {
     $loginMsg = $result->getMessages();

$authAdapter = new DbTable($dbAdapter, ‘user’, ‘username’, ‘password’, ‘MD5(?)’);

Above line says

First argument:- DBAdapterObject

Second argument:- “TABLENAME”

Third argument:- “USER_FIELD_NAME”

Fourth argument:- “USER_PASSWORD_FIELD_NAME”

Fifth argument:- “Encryption Method”


$authService = $this->serviceLocator->get('auth_service');

It is just the AuthenticationService object.

$authService = new AuthenticationService(new SessionStorage(‘auth’));



1 Comment

Leave a comment