Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Create Simple Login Authentication using AuthenticationService with rememberMe

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on October 23, 2012

Authentication is the process of verifying that “you are who you say you are”. Zend Framework 2 has an AuthenticationService component that usefull to handle this. It can use Adapters, like DbTable, Digest, Http, and Ldap with Session Storage that can be save until time we need by rememberMe() function from Session Manager.


For example, i have the following form like this to utilize rememberMe() function for authentication with DbTable adapter :

1. Prepare a Login Form with this entity.

//module/SanAuth/src/SanAuth/Model/User.php
namespace SanAuth\Model;

use Zend\Form\Annotation;

/**
 * @Annotation\Hydrator("Zend\Stdlib\Hydrator\ObjectProperty")
 * @Annotation\Name("User")
 */
class User
{
    /**
     * @Annotation\Type("Zend\Form\Element\Text")
     * @Annotation\Required({"required":"true" })
     * @Annotation\Filter({"name":"StripTags"})
     * @Annotation\Options({"label":"Username:"})
     */
    public $username;
    
    /**
     * @Annotation\Type("Zend\Form\Element\Password")
     * @Annotation\Required({"required":"true" })
     * @Annotation\Filter({"name":"StripTags"})
     * @Annotation\Options({"label":"Password:"})
     */
    public $password;
    
    /**
     * @Annotation\Type("Zend\Form\Element\Checkbox")
     * @Annotation\Options({"label":"Remember Me ?:"})
     */
    public $rememberme;
    
    /**
     * @Annotation\Type("Zend\Form\Element\Submit")
     * @Annotation\Attributes({"value":"Submit"})
     */
    public $submit;
}

Create custom Auth Storage that extends Zend\Authentication\Storage.

//module/SanAuth/src/SanAuth/Model/MyAuthStorage.php
namespace SanAuth\Model;

use Zend\Authentication\Storage;

class MyAuthStorage extends Storage\Session
{
    public function setRememberMe($rememberMe = 0, $time = 1209600)
    {
         if ($rememberMe == 1) {
             $this->session->getManager()->rememberMe($time);
         }
    }
    
    public function forgetMe()
    {
        $this->session->getManager()->forgetMe();
    } 
}

2. Register that into ServiceManager in Module class.

//module/SanAuth/Module.php
namespace SanAuth;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Authentication\Storage;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;

class Module implements AutoloaderProviderInterface
{
    public function getAutoloaderConfig(){/*common code*/}
    public function getConfig(){ /*common code*/}
    
    public function getServiceConfig()
    {
        return array(
            'factories'=>array(
		'SanAuth\Model\MyAuthStorage' => function($sm){
		    return new \SanAuth\Model\MyAuthStorage('zf_tutorial');  
		},
		
		'AuthService' => function($sm) {
                    //My assumption, you've alredy set dbAdapter
                    //and has users table with columns : user_name and pass_word
                    //that password hashed with md5
		    $dbAdapter           = $sm->get('Zend\Db\Adapter\Adapter');
                    $dbTableAuthAdapter  = new DbTableAuthAdapter($dbAdapter, 
                                              'users','user_name','pass_word', 'MD5(?)');
		    
		    $authService = new AuthenticationService();
		    $authService->setAdapter($dbTableAuthAdapter);
                    $authService->setStorage($sm->get('SanAuth\Model\MyAuthStorage'));
		     
		    return $authService;
		},
            ),
        );
    }

}

3. Create the Auth Controller

//module/SanAuth/src/SanAuth/Controller/AuthController.php
namespace SanAuth\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\View\Model\ViewModel;

use SanAuth\Model\User;

class AuthController extends AbstractActionController
{
    protected $form;
    protected $storage;
    protected $authservice;
    
    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()
                                      ->get('AuthService');
        }
        
        return $this->authservice;
    }
    
    public function getSessionStorage()
    {
        if (! $this->storage) {
            $this->storage = $this->getServiceLocator()
                                  ->get('SanAuth\Model\MyAuthStorage');
        }
        
        return $this->storage;
    }
    
    public function getForm()
    {
        if (! $this->form) {
            $user       = new User();
            $builder    = new AnnotationBuilder();
            $this->form = $builder->createForm($user);
        }
        
        return $this->form;
    }
    
    public function loginAction()
    {
        //if already login, redirect to success page 
        if ($this->getAuthService()->hasIdentity()){
            return $this->redirect()->toRoute('success');
        }
                
        $form       = $this->getForm();
        
        return array(
            'form'      => $form,
            'messages'  => $this->flashmessenger()->getMessages()
        );
    }
    
    public function authenticateAction()
    {
        $form       = $this->getForm();
        $redirect = 'login';
        
        $request = $this->getRequest();
        if ($request->isPost()){
            $form->setData($request->getPost());
            if ($form->isValid()){
                //check authentication...
                $this->getAuthService()->getAdapter()
                                       ->setIdentity($request->getPost('username'))
                                       ->setCredential($request->getPost('password'));
                                       
                $result = $this->getAuthService()->authenticate();
                foreach($result->getMessages() as $message)
                {
                    //save message temporary into flashmessenger
                    $this->flashmessenger()->addMessage($message);
                }
                
                if ($result->isValid()) {
                    $redirect = 'success';
                    //check if it has rememberMe :
                    if ($request->getPost('rememberme') == 1 ) {
                        $this->getSessionStorage()
                             ->setRememberMe(1);
                        //set storage again 
                        $this->getAuthService()->setStorage($this->getSessionStorage());
                    }
                    $this->getAuthService()->getStorage()->write($request->getPost('username'));
                }
            }
        }
        
        return $this->redirect()->toRoute($redirect);
    }
    
    public function logoutAction()
    {
        $this->getSessionStorage()->forgetMe();
        $this->getAuthService()->clearIdentity();
        
        $this->flashmessenger()->addMessage("You've been logged out");
        return $this->redirect()->toRoute('login');
    }
}

4. Create Success Controller

//module/SanAuth/src/SanAuth/Controller/SuccessController.php
namespace SanAuth\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class SuccessController extends AbstractActionController
{
    public function indexAction()
    {
        if (! $this->getServiceLocator()
                 ->get('AuthService')->hasIdentity()){
            return $this->redirect()->toRoute('login');
        }
        
        return new ViewModel();
    }
}

5. Register controller invokables, router, and view_manager into module.config.php

return array(
    'controllers' => array(
        'invokables' => array(
            'SanAuth\Controller\Auth' => 'SanAuth\Controller\AuthController',
            'SanAuth\Controller\Success' => 'SanAuth\Controller\SuccessController'
        ),
    ),
    'router' => array(
        'routes' => array(
            
            'login' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/auth',
                    'defaults' => array(
                        '__NAMESPACE__' => 'SanAuth\Controller',
                        'controller'    => 'Auth',
                        'action'        => 'login',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'process' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:action]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
            
            'success' => array(
                'type'    => 'Literal',
                'options' => array(
                    'route'    => '/success',
                    'defaults' => array(
                        '__NAMESPACE__' => 'SanAuth\Controller',
                        'controller'    => 'Success',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:action]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
            
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'SanAuth' => __DIR__ . '/../view',
        ),
    ),
);

6. Create a login view :

//module/SanAuth/view/san-auth/auth/login.phtml
$form = $this->form;
$form->setAttribute('action', $this->url(
    'login/process',
    array(
        'action'     => 'authenticate',
    )
));
$form->prepare();

echo $this->form()->openTag($form);
echo $this->formCollection($form);
echo $this->form()->closeTag();

if ($this->messages){
    echo '<ul>';
    foreach($this->messages as $message)
    {
        echo '<li>'.$message.'</li>';
    }
    echo '</ul>';
}

7. The success view

<!-- //module/SanAuth/view/san-auth/success/index.phtml -->
Login Success.
<br />

<a href="<?php echo $this->url('login/process', array('action'=>'logout')); ?>">Logout</a>

Btw, I publish this sourcecode into my github account : https://github.com/samsonasik/SanAuth .

Reference :
http://en.wikipedia.org/wiki/Authentication

Advertisements

525 Responses

Subscribe to comments with RSS.

  1. Stillmatic said, on October 23, 2012 at 1:11 pm

    Very nice work! Does this implementation save the logged in users in a session database? I dont think so, but do you plan to implement it ? I cant get it to work and it would be nice to see a working example.
    Thanks!

  2. samsonasik said, on October 23, 2012 at 2:13 pm

    Thanks. Not yet, but it can. just create a function to save into db if login is validated. This is just a simple example. I think it would be nice. I hope i can update the blog and source code(s) regularly ;). You’re welcome

    • Visvanathan said, on March 31, 2014 at 2:48 pm

      I need Your help In zf2 pls contact me on itsvishwa01@gmail.com

    • Ahammad karim said, on May 11, 2014 at 2:31 pm

      Dear Author,
      I am trying to use your login sample. I found a problem. In Auth controller AuthenticateAction : if i used this
      //check if it has rememberMe :
      if ($request->getPost(‘rememberme’) == 1 ) {
      $this->getSessionStorage() ->setRememberMe(1);
      //set storage again
      $this->getAuthService()->setStorage($this->getSessionStorage());
      }
      $this->getAuthService()->getStorage()->write($request->getPost(‘username’));

      Then hasIdentity() return 0 in success controller and redirect to login page. if i remove this then hasIdentity() getting 1. What is happening in my case.

    • Ahammad karim said, on May 11, 2014 at 2:33 pm

      Dear Author,
      I am trying to use your login sample. I found a problem. In Auth controller AuthenticateAction : if i used this
      //check if it has rememberMe :
      if ($request->getPost(‘rememberme’) == 1 ) {
      $this->getSessionStorage() ->setRememberMe(1);
      //set storage again
      $this->getAuthService()->setStorage($this->getSessionStorage());
      }
      $this->getAuthService()->getStorage()->write($request->getPost(‘username’));

      Then hasIdentity() return 0 in success controller and redirect to login page. if i remove this then hasIdentity() getting 1. What is happening in my case.

  3. Li said, on October 24, 2012 at 5:58 am

    Excellent tutorial samsonasik, thanks.
    I have question, Why the class user? I not understand.
    Sorry, my English isn’t good.

  4. samsonasik said, on October 24, 2012 at 2:11 pm

    You’re welcome. Ah, i was Typo Student, that should be User. Thank you. I write User because the form is created by entity. You can change to your desired name, for example, LoginForm or other.

    Btw, if you’re not fan with Annotation builder, you can create your form by extends Zend_Form.

  5. houssemzaier said, on October 26, 2012 at 4:05 am

    Thank you so much my friend for your tutorial that works good 🙂

  6. Birzat said, on October 30, 2012 at 11:29 pm

    Hi,

    Thanks for your explication.

    Is it possible that you explain this in detail :

    ‘SanAuth\Model\MyAuthStorage’ => function($sm){
    return new \SanAuth\Model\MyAuthStorage(‘zf_tutorial’);
    },

    ‘AuthService’ => function($sm) {
    //My assumption, you’ve alredy set dbAdapter
    //and has users table with columns : user_name and pass_word
    //that password hashed with md5
    $dbAdapter = $sm->get(‘Zend\Db\Adapter\Adapter’);
    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,
    ‘users’,’user_name’,’pass_word’, ‘MD5(?)’);

    $authService = new AuthenticationService();
    $authService->setAdapter($dbTableAuthAdapter);
    $authService->setStorage($sm->get(‘SanAuth\Model\MyAuthStorage’));

    return $authService;
    },

    Thanks

  7. sumbersoft said, on November 2, 2012 at 11:24 am

    mantab gan. Baru belajar zf 2 ne susah banget cari referensinya.
    btw ini tiap controller dan router apa emang harus diregistrasi di config/module.config.php?
    klo 1 controller aja bisa sampe 10 baris ntar apa ga susah ngeditnya? ato ada tips triknya?

    Makasie

    • samsonasik said, on November 2, 2012 at 2:23 pm

      zf2 mementingkan performance, lagian, kan banyak keuntungan. keys dari servicemanager kan ga cuma invokables. misal, via factories, kita bisa meng-inject itu controller untuk melakukan sesuatu dulu, mengeset property misalnya,nah, ini bisa mensimplifikasi kode di controller kelak. contoh :

      'controllers'=> array(
           'factories' => array(
                  'SanAuth\Controller\Auth' => function($sm) {
                        $controller = new   \SanAuth\Controller\AuthController;
                        $controller->setAuth($sm->get('AuthService'));
                  },
          ),
      ),
      

      Nah, di controllernya :

      class AuthController
      {
          protected $authservice;
          
          public function setAuth($auth)
          {
                 $this->authservice = $auth;
          }
      
          public function dosomethingAction()
          {
                  $this->authservice->authenticate(); 
                 // $this->authservice otomatis bisa dipakai krn udah keinject.
          }
      }
      

      Nah, si setAuth($auth) udah otomatis dah keeksekusi dari ServiceManager nya. karena controllers keys untuk service manager otomatis dieksekusi pas proses mvc stack.

      Kalau soal bikin berulang kali, ya intinya jangan buat controller baru kalau tidak diperlukan. 😉

  8. sumbersoft said, on November 2, 2012 at 12:54 pm

    btw cara ganti pesan A record with the supplied identity could not be found. lewat mana? bisa minta referensinya?

    Thanks

    • samsonasik said, on November 2, 2012 at 2:25 pm

      dari

      $result = $this->getAuthService()->authenticate();
      

      kamu bisa dapatkan

      $result->getCode()
      

      nya.

      Nah, tinggal dicoba deh seperti ini :

      
      switch ($result->getCode()) {
      
          case Result::FAILURE_IDENTITY_NOT_FOUND:
              /** do stuff for nonexistent identity **/
              break;
      
          case Result::FAILURE_CREDENTIAL_INVALID:
              /** do stuff for invalid credential **/
              break;
      
          case Result::SUCCESS:
              /** do stuff for successful authentication **/
              break;
      
          default:
              /** do stuff for other failure **/
              break;
      }
      

      Bisa baca ini deh : http://zf2.readthedocs.org/en/latest/modules/zend.authentication.intro.html

  9. dimuthu said, on November 9, 2012 at 9:09 am

    Hi Samsonik,
    How do we show the user fullname from the database?.
    TQs

  10. samsonasik said, on November 9, 2012 at 9:44 am
     print_r($this->getAuthService()->getAdapter()->getResultRowObject());
    

    read the docs : http://zf2.readthedocs.org/en/latest/modules/zend.authentication.adapter.dbtable.html

  11. hakopsp said, on November 9, 2012 at 9:18 pm

    Hi,

    Thanks for this tutorial of yours! I’m totally new to zend framework 2 and would like to ask you regarding this example of yours. In the zend website tutorial, the folder under /view is /album/album. So I assume that is the format. However in your example, you have /auth and /view under /view/san-auth instead of /view/san-auth/san-auth. Why is that so and how does the framework know where the retrieve the relevant phtml files?

    Hako

  12. Pedro J. said, on November 12, 2012 at 1:20 am

    Hello Samsonasik,

    Thanks for your nice Zend2 and Login Remember ME introduction. Unfortunately I have a problem with the Login formular.
    In my test with the Album create, change delete and new if I open http://www.domain.de/auth I miss the following fields:
    Username
    Pass and
    Remember Me.

    I have seen this ony once.

    Within the Apache Log in I don’t receive an error message or comment about the problem.

    Can you please advice?

    Thanks in advance and regards,

  13. samsonasik said, on November 12, 2012 at 11:54 am

    check via $_SESSION global var.

  14. Pedro J. said, on November 12, 2012 at 6:44 pm

    He, samsonasik,
    see what am I doing here var_dump($_SESSION)?

    object(Zend\Session\Storage\SessionStorage)#203 (2) {
    [“isImmutable”:protected]=>
    bool(false)
    [“storage”:”ArrayObject”:private]=>
    array(2) {
    [“__ZF”]=>
    array(1) {
    [“_REQUEST_ACCESS_TIME”]=>
    float(1352709310.2749)
    }
    [“FlashMessenger”]=>
    object(ArrayObject)#250 (1) {
    [“storage”:”ArrayObject”:private]=>
    array(0) {
    }
    }
    }
    }

    • samsonasik said, on November 13, 2012 at 12:50 am

      i think session writing process was failed, check before redirecting after login succeded.

  15. Pedro J. said, on November 14, 2012 at 3:59 am

    Hi,
    where I have to start writing the session?

    Thank
    Pedro

    • samsonasik said, on November 14, 2012 at 8:01 am

      for standalone usage, you can instantiate Zend\Session\Container

  16. Guilhem said, on November 14, 2012 at 10:20 pm

    Thanks from London, your tutorials are unbelievable

  17. dimuthu said, on November 16, 2012 at 4:44 pm

    Hey man,
    do you have any source code for user authentication with acl?

  18. samsonasik said, on November 16, 2012 at 7:05 pm

    Zend\Authentication is for authentication.
    Zend\Permission\Acl is for authorization.

    I’ve write an example using acl here : https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/ , i hope it will help, but if you will built in , you can find them on here https://github.com/ZF-Commons

  19. Dragos said, on November 16, 2012 at 9:41 pm

    Hello. When you have time please tell me what is the best way to manage a navigation, a general site navigation not from config but from database. i try to find an aproach of this in zf2 but i can’t find. Maybe do a blog post with only this subject or please give 2-3 guidlines. tank you

  20. samsonasik said, on November 17, 2012 at 12:32 am

    it’s a good idea, thanks.

  21. dimuthu said, on November 28, 2012 at 4:08 pm

    Hi samsonasik,
    how can i load different layout after the login success?aslo how do pass the common controller data to the layout
    ?
    TQs

  22. Harry said, on December 5, 2012 at 5:19 pm

    could you tell me how get the user name stored in future or in other module?

    $this->getServiceLocator()->get(‘AuthService’)->getStorage()->read()?

    • samsonasik said, on December 5, 2012 at 5:38 pm

      calling from controller action :

      if ($this->getServiceLocator()->get('AuthService')->hasIdentity()) {
          $users = $this->getServiceLocator()->get('AuthService')->getStorage()->read(); 
          echo $users['username'];
      }
      

      calling from Module.php

      use Zend\Mvc\MvcEvent;
      
      class Module
      {
          public function onBootstrap(MvcEvent $e)
          {
                  $application = $e->getApplication();
                  $sm = $application->getServiceManager();
                  if (! $sm->get('AuthService')->hasIdentity()) {
                      $users = $sm->get('SanAuth\Model\AuthStorage')->read();
                      echo $users['username'];
                 }
          }
      }
      
      • Gabriel Acosta said, on May 16, 2013 at 8:16 pm

        Since working with the user info is something very common what I do is after:

        $result = $this->getAuthService()->authenticate();

        I do

        $ommit = array(‘password’);
        $_SESSION[‘User’] = $this->getAuthService()->getAdapter()->getResultRowObject(null,$ommit);
        And so I have the User Object in memmory, then When I do Logout I erase it from memory.

        One question for you samsonasik though, I’m learning ZF2 so I don’t understand why this work like this, on logout action, if I do:

        public function logoutAction()
        {
        unset($_SESSION[‘User’]);
        $this->getSessionStorage()->forgetMe();
        $this->getAuthService()->clearIdentity();

        $this->flashmessenger()->addMessage(“You’ve been logged out”);
        return $this->redirect()->toRoute(‘login’);
        }
        It apears ZF2 ignores my code, but if I do

        public function logoutAction()
        {
        $this->byebye();
        $this->getSessionStorage()->forgetMe();
        $this->getAuthService()->clearIdentity();

        $this->flashmessenger()->addMessage(“You’ve been logged out”);
        return $this->redirect()->toRoute(‘login’);
        }
        public function byebye()
        {
        unset($_SESSION[‘User’]);
        }

        Then it works!!! Do you know why?

      • samsonasik said, on May 17, 2013 at 12:28 pm

        don’t mix native php function with framework. define namespace to Session component if you want other needed.

  23. pov said, on December 27, 2012 at 5:37 pm

    Hi
    I am new in ZF. I just want test this example but i have problem with point 5. I don’t know where i should write this code. please help me to fix it

    thanks

    • samsonasik said, on December 28, 2012 at 3:44 am

      in Yourmodule/config/module.config.php

      • pov said, on December 28, 2012 at 8:22 am

        thanks you! you are a creative admin! (y)

      • samsonasik said, on December 28, 2012 at 1:10 pm

        You’re welcome 😉

  24. Igor said, on December 28, 2012 at 5:45 pm

    I has received “incorrect redirection” in routes, how to fix it?

    thanks

  25. Igor said, on December 29, 2012 at 2:28 am

    I so copy and paste your code, nothing more.
    Please see my code https://github.com/IgorDePaula/module-teste-zend-2

    • samsonasik said, on December 29, 2012 at 1:47 pm

      Clone from my github : https://github.com/samsonasik/SanAuth

    • Igor said, on January 2, 2013 at 9:49 pm

      the error is that both the tutorials are incompatibles, don’t complement.

      • Igor said, on January 2, 2013 at 9:50 pm

        They execute alone, but joined no.

      • samsonasik said, on January 2, 2013 at 10:11 pm

        just work for me. i’m using latest zf2 2.0.6 version. i’m using acl and authentication in my prj, and it’s worked :). Authentication is different with Authorization. Authorization is about resource that user can(not) ‘see’, Authentication is about what user must do before access resource(s)

      • Igor said, on January 2, 2013 at 10:23 pm

        yeah, I’m using version 2.0.6 too, but so copy and past yout code is not sufficient. I know the differenc between authorization and authentication, I look for help in your tutotials, just so it. The form that you use they in your project is different od tutoriails written.

      • samsonasik said, on January 2, 2013 at 10:30 pm

        please give me specific error, so i can help you 🙂

      • Igor said, on January 2, 2013 at 10:38 pm

        if I use only the code this tutorial, he does execute perfectly, but if i joined with other tutorial (https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/) occur route error, incorrect redirection, i think that the error is where was defined the acl rules, he doesnot recognized the route.

      • samsonasik said, on January 2, 2013 at 10:53 pm

        You can’t redirect to route that not registered. based on my post, try to change with :

        $url    = $router->assemble(array(), array('name' => 'auth'));
        
      • Igor said, on January 2, 2013 at 11:04 pm

        i tried this form, i tried with login, login/process, and does not excecute too.

      • samsonasik said, on January 2, 2013 at 11:12 pm

        try to redirect manually, by native php header(‘location’). i’m curious this is apache problem.

      • Igor said, on January 2, 2013 at 11:11 pm

        Message:

        Route with name “auth” not found

      • samsonasik said, on January 2, 2013 at 11:17 pm

        Ooops, the route i mean named ‘login’ :). It’s weird, module.config should already merged if configured correctly, becase just work for me :). have your module Auth with module Authorization already registered in config/application.config.php ??

      • Igor said, on January 2, 2013 at 11:38 pm

        manually don’t work too, in true i created a module called Test and put your code ther. You cite Apache, i use zend server ce.

      • samsonasik said, on January 3, 2013 at 12:08 am

        To test something trouble with your web server configuration. try to create a simple app with native php and redirect with header(‘location: somethingelsepage.php’);. If you found a problem with it, try to update/upgrade your web server/container, and Follow the instruction on zf docs.

      • Igor said, on January 3, 2013 at 12:12 am

        No, i haven’t problem with this header. I have put this codes in different modules?

      • samsonasik said, on January 3, 2013 at 12:36 am

        No. Sorry. I have no idea with your problem. if you already register your module in config/application.config.php , it should be worked :). debug with write url in your browser without redirect, make sure everything alright, call ‘redirect’ with manual header location, if it’s work, it’s your route config/acl config problem. i can’t help more than this 😉

      • Igor said, on January 3, 2013 at 12:40 am

        and if I put the code in a repository, can you see him and look for an error?

      • samsonasik said, on January 3, 2013 at 12:45 am

        just try it 🙂

      • Igor said, on January 3, 2013 at 12:56 am

        https://github.com/IgorDePaula/module-teste-zend-2, look, please…

      • samsonasik said, on January 3, 2013 at 1:46 am

        1. You should place SuccessController in your src/Teste/Controller folder.
        2. in this case, getSessContainer() should call servicelocator that call AuthService.

            private function getSessContainer()
            {
                if (!$this->sesscontainer) {
                    $this->sesscontainer = $this->getController()->getServiceLocator()
                            ->get('AuthService')->getStorage();
        	    
                }
                return $this->sesscontainer;
            }
        

        and change the code get role in doAuthorization($e) function.

        $locator  = $e->getController()->getServiceLocator();
        if (! $this->getController()->getServiceLocator()
                            ->get('AuthService')->hasIdentity()) {
               $role = 'anonymous';
        } else {
             $username = $this->getSessContainer()->read();
             $role = //find role by username... somehing like this 
                        //it's your code to find the role by username
                    $locator->get('Rolefinder')->get($username);
        }
        

        Btw, try to debug by print_r and die the data you getted :).

      • Igor said, on January 3, 2013 at 2:09 am

        Fatal error: Call to a member function getServiceLocator() on a non-object in C:\Zend\Apache2\htdocs\ZendSkeletonApplication\module\Teste\src\Teste\Plugin\ControllerManager.php on line 57

        in your change in doAuthorization , and before he does not findo auth route…https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/#comment-3801

      • samsonasik said, on January 3, 2013 at 2:15 am

        Oops, use $this instead $e in getting servicelocator.

        $locator  = $this->getController()->getServiceLocator();
        

        i mean :).

    • Igor said, on January 3, 2013 at 2:24 am

      the following continue: Message:

      Route with name “auth” not found

      • Igor said, on January 3, 2013 at 2:25 am

        public function doAuthorization($e) {
        //setting ACL…
        $acl = new Acl();
        //add role ..
        $acl->addRole(new Role(‘anonymous’));
        $acl->addRole(new Role(‘user’), ‘anonymous’);
        $acl->addRole(new Role(‘admin’), ‘user’);

        $acl->addResource(new Resource(‘Application’));
        $acl->addResource(new Resource(‘Teste’));
        $acl->addResource(new Resource(‘Auth’));
        $acl->addResource(new Resource(‘Success’));

        $acl->deny(‘anonymous’, ‘Application’, ‘view’);
        $acl->deny(‘anonymous’, ‘Teste’, ‘Teste’);

        $acl->allow(‘anonymous’, ‘Teste’, ‘Auth’);
        // $acl->allow(‘anonymous’, ‘Auth’, ‘login’);
        // $acl->allow(‘anonymous’, ‘Auth’, ‘auth’);
        $acl->allow(‘user’, ‘Teste’, ‘Success’);

        $acl->allow(‘user’, array(‘Application’), array(‘view’));

        //admin is child of user, can publish, edit, and view too !
        $acl->allow(‘admin’, array(‘Application’, ‘Teste’), array(‘publish’, ‘edit’));

        $controller = $e->getTarget();
        $controllerClass = get_class($controller);
        $namespace = substr($controllerClass, 0, strpos($controllerClass, ‘\\’));

        // exit($this->getSessContainer()->role );

        // $role = (!$this->getSessContainer()->readrole ) ? ‘anonymous’ : $this->getSessContainer()->role;
        //

        $locator = $this->getController()->getServiceLocator();
        if (! $this->getController()->getServiceLocator()
        ->get(‘AuthService’)->hasIdentity()) {
        $role = ‘anonymous’;
        } else {
        $username = $this->getSessContainer()->read();
        $role = //find role by username… somehing like this
        //it’s your code to find the role by username
        $locator->get(‘Rolefinder’)->get($username);
        }
        if (!$acl->isAllowed($role, $namespace, ‘index’)) {
        $router = $e->getRouter();
        $url = $router->assemble(array(), array(‘name’ => ‘auth’)); //exit($url);
        $response = $e->getResponse();

        $response->setStatusCode(302);
        //redirect to login route…

        $response->getHeaders()->addHeaderLine(‘Location’, $url);

        }
        }

      • samsonasik said, on January 3, 2013 at 2:29 am

        Your route named ‘login’

      • Igor said, on January 3, 2013 at 5:09 pm

        route maned login do not working too.

      • samsonasik said, on January 3, 2013 at 6:23 pm

        Have you try to set priority to – ( negative ) into sharedeventmanager ? if problem still exist, try to not pass into controller plugin, create a function to handle acl in your module class, and attach eventmanager from bootsrap with it

      • Igor said, on January 3, 2013 at 6:28 pm

        when I change the route auth for route login, cause incorrect redirection, but my code is equals your code. But i think you writte other tutorial integrating the authorization and acl?

      • samsonasik said, on January 3, 2013 at 8:03 pm

        good idea :), thanks

  26. Josias Duarte said, on December 30, 2012 at 3:23 pm

    It seems that the rememberMe() is not working, it doesn’t have any difference when the remember checkbox is checked. I also realised that if I don’t check remember me and restart the browser, it still logged. For what I see it don’t use cookies, just SESSION. Can u explain me how rememberMe() works?

    p.s. If it changes the SESSION duration, this duration doesn’t affect other SESSIONS from the system?

    • samsonasik said, on December 30, 2012 at 4:00 pm

      Have you try to set set session.cookie_lifetime = 0 in php.ini ?

      • Josias Duarte said, on December 31, 2012 at 12:58 am

        Yeh, I checked, it’s 0. I don’t know what is going on! I made another test: set an SESSION from the view manully ($SESSION[‘teste’] = ‘testValue’), and closed the browser, when I reopened It was still there! The right behavior is all inset all SESSION when I close the browser right?

      • samsonasik said, on December 31, 2012 at 8:25 am

        Yes. it should be worked. i think it’s php.ini config problem, or your web container setting :). Maybe you should check other variable, like “session.use_only_cookies”

      • Josias Duarte said, on December 31, 2012 at 9:15 am

        OMG, the browser was restoring the last session, because every time I opened it, I didn’t want to type the domain, so I was just going to the history. This is embarrassing.

        It’s working! But I just want to know if there’s some way to do the remember me with cookies in ZF2. And I need it to work with the subdomains too, so the domain in the cookie must be ‘.mydomain.com’ and not just ‘mydomain.com’. There’s come way I can achieve this in ZF2?

        Thanks for your help man!

      • samsonasik said, on January 1, 2013 at 1:53 pm

        set your session.cookie_domain = “.yourdomain.com” . ZF2 use cookie for remember-ing the session. You’re welcome.

      • Oleg Abrazhaev said, on January 31, 2014 at 10:34 am

        How to configure not use cookie for saving rememberme token, but use db table?

  27. Josias Duarte said, on January 3, 2013 at 7:16 am

    Hey! Do you know same way to get the configuration from config/autoload/global.php inside the init() method in the Module.php?
    inside onBootstrap() I can do it like this:
    $config = $e->getApplication()->getServiceManager()->get(‘Configuration’);

    but in the init() I don’t know how to do it. What I want is define an array in the config file with pairs ‘constantName’=>’constantValue’, so inside the init() I loop through this array and define my app constants!

    • samsonasik said, on January 4, 2013 at 2:33 pm

      maybe like this :

      use Zend\ModuleManager\ModuleManager;
      
      class Module
      {
          public function init(ModuleManager $modulemanager)
          {
      	$sharedEvents = $modulemanager->getEventManager()->getSharedManager();
      	$sharedEvents->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
      	   $config = $e->getApplication()->getServiceManager()->get('Config');
      	   
                 echo '<pre>';
      	   print_r($config);
      	   echo '</pre>';
              });
          }
      }
      
      • Josias Duarte said, on January 4, 2013 at 8:10 pm

        Thank you man! Your replies have been very helpful!

      • samsonasik said, on January 5, 2013 at 5:58 am

        You’re welcome 😉

  28. Igor said, on January 7, 2013 at 6:39 pm

    I find 1 error in your code: I tryed get the level of user, when return null, i debugued the code and find that the right code is

    $role = (! $this->getSessContainer()->storage->role ) ? ‘anonymous’ : $this->getSessContainer()->storage->role;

    and not

    $role = (! $this->getSessContainer()->role ) ? ‘anonymous’ : $this->getSessContainer()->role;

  29. Ibrahim said, on January 7, 2013 at 11:30 pm

    Quick question (sarcasm):

    I would like to know how to make \Zend\Session use a database table, instead of $_SESSION. Seeing as the documentation is not complete, I was wondering if you might want to write a blog post about this subject?

  30. Arpita Rana said, on January 8, 2013 at 12:01 pm

    Here is authentication example with ZF2 with doctrine but how with only ZF2 without doctrine

  31. Arpita Rana said, on January 8, 2013 at 1:18 pm

    Where is extends Zend\Form\Form ?
    I m learner of ZF2.
    Thanks in advance.

  32. Arpita Rana said, on January 8, 2013 at 2:30 pm

    Thanks but i want to integrate ZF with doctrine so please help me how do it?
    and i follow your above example that time I got an error
    Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in D:\ZendSkeletonApplication\vendor\zendframework\zendframework\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 46

    and already i install doctrine library in my vendor folder So please help me..

  33. Arpita Rana said, on January 9, 2013 at 6:01 pm

    Hi samsonasik,
    Here we check it in indexAction of successController

    if (! $this->getServiceLocator()
    ->get(‘AuthService’)->hasIdentity()){
    return $this->redirect()->toRoute(‘login’);
    }

    instead of check it in every action I want to check it in every request of page at one place
    so I think it will be in onBootstrap() function in module.php

    And for it I need action and controller name in that file.

    So,
    how can I get an action and controller name in Module.php file ?
    how can check identity there?
    how can redirect in that file.?

    Thanks in advace.

    • samsonasik said, on January 10, 2013 at 5:26 am

      maybe something like this :

      namespace SanCommons;
      
      use Zend\Mvc\MvcEvent,
          Zend\ModuleManager\Feature\AutoloaderProviderInterface,
          Zend\ModuleManager\Feature\ConfigProviderInterface;
      
      class Module implements
          AutoloaderProviderInterface,
          ConfigProviderInterface
      {
          public function onBootstrap(MvcEvent $e)
          {
              $eventManager        = $e->getApplication()->getEventManager();
              $eventManager->attach('route', array($this, 'AuthCheck'), 2);
          }
      
          public function AuthCheck(MvcEvent $e)
          {
              $application   = $e->getApplication();
      	$sm            = $application->getServiceManager();
      	
              $router        = $sm->get('router');
      	$request       = $sm->get('request');
      	
      	$matchedRoute = $router->match($request);
      	if (null !== $matchedRoute) {
                  $controller = $matchedRoute->getParam('controller');
                  $action = $matchedRoute->getParam('action');
                  
                  // check auth...
                  $response = $e->getResponse();
                  if (! $sm->get('AuthService')->hasIdentity()){
                       $url    = $router->assemble(array(), array('name' => 'login'));
                       
                       $response->setStatusCode(302);
                       $response->getHeaders()->addHeaderLine('Location', $url);
                  }
              }
          }
          public function getAutoloaderConfig(){ /*common code */}
          public function getConfig(){ /* common code */ }
      }
      
      • Arpita Rana said, on January 11, 2013 at 11:45 am

        Thank you very much it is very useful to me.

      • samsonasik said, on January 11, 2013 at 2:05 pm

        You’re welcome 😉

  34. Dr.Dre said, on January 10, 2013 at 12:14 am

    Hi Abdul,

    useful as usual.

    What should I do if I want to use a crypt password? I know I can use the Zend\Crypt\Password\Bcrypt class, but I’m not sure about how modify the AuthService

    actual code:
    /* ****
    *
    */
    ‘AuthService’ => function($sm) {
    $dbAdapter = $sm->get(‘Zend\Db\Adapter\Adapter’);
    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,
    ‘user’,’username’,’password’, ‘SHA1(SHA1(?))’); //double SHA1 to avoid fast dictionary recognition

    $authService = new AuthenticationService();
    $authService->setAdapter($dbTableAuthAdapter);
    $authService->setStorage($sm->get(‘Admin\Model\MyAuthStorage’));

    return $authService;
    },

    • samsonasik said, on January 10, 2013 at 5:49 am

      In your case, for DbTableAuthAdapter, don’t pass a treatment :

      $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,'user','username','password'); 
      

      and pass your secured data to setCredential in authentication process:

      use Zend\Crypt\Password\Bcrypt;
      $bcrypt = new Bcrypt();
      $securedpassword = $bcrypt->create($request->getPost('password'));
      
      $this->getAuthService()->getAdapter()
             ->setIdentity($request->getPost('user'))
             ->setCredential($securedpassword);
      
      • Dr.Dre said, on January 10, 2013 at 7:13 pm

        It is exactly what I’ve tried as first attempt, but the Bcrypt-ed password change every time and the ->authenticate() method does not have the right output while the Bcrypt method “verify()” does.

        I might try either
        1) to change the authService, maybe changing the DbTable with a TableGateway and work directly using the verify() method
        or
        2) I can create my own authenticateSecure() method, extending Zend\Authentication\Adapter\DbTable? I can override the default method only declaring it again, am I right?

      • Dr.Dre said, on January 10, 2013 at 7:35 pm

        add: verify() method needs the uncrypted password as param.

        Do you know if there is a method similar to authenticate but for Bcrypt class?

      • samsonasik said, on January 11, 2013 at 7:01 am

        not yet, i will take a look at that.

      • samsonasik said, on January 12, 2013 at 3:58 am

        Hey, Dr. Dre,

        based on this article : http://www.zimuel.it/en/english-cryptography-made-easy-with-zend-framework/
        You should setSalt first :

        $bcrypt->setSalt('vlAzj20g2e7.x8s3sm5dLbLkFOw.Qa');
        

        before create :

        $bcrypt->create($request->getPost('password'));
        
      • cb said, on February 8, 2015 at 8:03 pm

        but isn’t a little limiting to always use the same salt? using just bcrypt and verify is pb the better way..

      • samsonasik said, on February 9, 2015 at 10:04 am

        yes!, that’s better ;). I was just answering the question 😉

  35. Dr.Dre said, on January 15, 2013 at 5:51 pm

    Only as feedback: I’ve not tried it yet, but thank you anyway. At the moment It works extending the class, but in a second moment I can revise the whole code and try this (less code is better, but not always you have the time to set up all the stuff in the best way).

    I’m looking forward for your next blog entries and, only as a suggestion, you can write something about routing, url aliases and friendly urls generation.

    • samsonasik said, on January 15, 2013 at 9:31 pm

      good idea, thanks.

    • samia said, on June 3, 2013 at 9:30 pm

      Hi Dr. Dre,

      Can you give me an example of how you have tried using bcryp. I am currently facing the same issue as you did. Thanks,

      Samia

  36. Josias Duarte said, on January 16, 2013 at 3:42 am

    Hey Sam, do you know some way I can do a user widget/plugin so that I can use it in every single page of my website? It would be a user bar on the top of every page, if a user is logged, it shows something like a user avatar, account settings, favorites, etc. If no user is logged, show links like “sign up”, “sign in”… I will need this and I don’t know how to achieve this, do you have some tips?

    • samsonasik said, on January 16, 2013 at 4:02 am

      you can set it in layout by injecting layout variable. It can be done via Module.php

      class Module
      {
          public function onBootstrap(MvcEvent $e)
          {
              $eventManager   =    $e->getApplication()->getEventManager();
              //load Common Vars
              $eventManager->attach('dispatch', array($this, 'loadCommonViewVars'), 100);
          }
          
          public function loadCommonViewVars(MvcEvent $e)
          {
              $e->getViewModel()->setVariables(array(
                  'loginbtn' => ($e->getApplication()
                                  ->getServiceManager()->get('AuthService')->hasIdentity()) ? 'Go to Profile' : 'Login'
              )); 
          }
      }
      

      and you can call it in the layout :

      <?php echo $this->layout()->loginbtn; ?>
      
  37. Josias Duarte said, on January 16, 2013 at 4:18 am

    Thanks! I’ll try it out!

  38. Blitzk said, on January 16, 2013 at 2:54 pm

    Your tutorial was helpful! I altered the table to include a column ‘salt’. I generated password by concatenating the password with salt and then passing the concatenated string to md5 function.

    So, in module.php, I did following but couldn’t get the code to work:

    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, ‘users’,’user_name’,’pass_word’, ‘MD5(CONCAT(?, salt))’);

    I am getting a message: The supplied parameters to DbTable failed to produce a valid sql statement, please check table and column names for validity.

    Waiting for your reply.

    • samsonasik said, on January 17, 2013 at 12:12 am

      if column salt is exist, it should be work. try to update you zf2 to the latest master here : https://github.com/zendframework/zf2/

      • Blitzk said, on January 17, 2013 at 1:34 pm

        Thanks for the reply. But, I am using ZF 2.0.6. I have created the password by combining the password and salt column and then generating the md5 of the combined string for example: md5(concat(password, salt)).

      • samsonasik said, on January 17, 2013 at 4:32 pm

        i’m using git to sync local and github master branch, and just work 🙂

    • Xavier Tuà said, on January 29, 2013 at 2:55 am

      Do you use a latin codification in datatable fields(password and salt)? I changed it to utf8 and It worked! 😉 Hope it helps you

  39. carl said, on January 21, 2013 at 10:16 am

    I clone your code on git,nothing more.But,I get some error:HTTP error 500(Internal Server Error).
    Please see my code https://github.com/excellnn/myself

  40. joenilson said, on January 22, 2013 at 11:35 am

    Hi samsonasik, i’m trying to use this lines:

    $dbAdapter = $sm->get(‘Zend\Db\Adapter\Adapter’);
    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,’users’,’user_name’,’pass_word’, ‘MD5(?)’);

    But using the 3 vars from the zend framework 2 db authentication documentation:

    ->setCredentialTreatment(“MD5(CONCAT(‘$hardcodedSalt’ , ? , salt))”);

    But when the login try to exec the sql it receive the error:

    SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data type of parameter $1

    this is because i’m putting two parameters, but i dont understand if it is in the documentation must to work, or is someting that i’m doing in the wrong way?.

  41. […] von 2 weiteren Tutorials: Zend Framework 2: Authentication + Acl using EventManager | P0L0's Blog Zend Framework 2 : Create Simple Login Authentication using AuthenticationService with rememberMe Letztenendes habe ich mich dann für eine Art Mischmasch entschieden, ein eigenes Modul das […]

  42. Vivek Khurana said, on February 11, 2013 at 4:34 pm

    Hi!
    I copied your code and I get this error

    PHP Fatal error: Uncaught exception ‘Zend\\ModuleManager\\Listener\\Exception\\InvalidArgumentException’ with message ‘Config being merged must be an array, implement the \\Traversable interface, or be an instance of Zend\\Config\\Config. NULL given.’ in /opt/justbtl/zf2/ZendSkeletonApplication/vendor/ZF2/library/Zend/ModuleManager/Listener/ConfigListener.php:324\nStack trace:\n#0

    /opt/justbtl/zf2/ZendSkeletonApplication/vendor/ZF2/library/Zend/ModuleManager/Listener/ConfigListener.php(130): Zend\\ModuleManager\\Listener\\ConfigListener->addConfig(‘SanAuth’, NULL)\n#1 [internal function]: Zend\\ModuleManager\\Listener\\ConfigListener->onLoadModule(Object(Zend\\ModuleManager\\ModuleEvent))\n#2 /opt/justbtl/zf2/ZendSkeletonApplication/vendor/ZF2/library/Zend/EventManager/EventManager.php(460): call_user_func(Array, Object(Zend\\ModuleManager\\ModuleEvent))\n#3 /opt/justbtl/zf2/ZendSkeletonApplication/vendor/ZF2/library/Zend/EventManager/EventManager.php(204): Zend\\EventManager\\EventManager->triggerListeners(‘loadModule’, Object(Zend\\ModuleManager\\Mo in /opt/justbtl/zf2/ZendSkeletonApplication/vendor/ZF2/library/Zend/ModuleManager/Listener/ConfigListener.php on line 324

    I have cross checked that all the files are in the places they are supposed to be. I am using zend framework 2.1 and zend skeleton app as mentioned in the documentation.

    regards

    • samsonasik said, on February 11, 2013 at 4:55 pm

      in Module.php, fill following functions with common functions of Module class.

      //module/SanAuth/Module.php
      .............
          public function getAutoloaderConfig()
          {
              return array(
                  'Zend\Loader\ClassMapAutoloader' => array(
                      __DIR__ . '/autoload_classmap.php',
                  ),
                  'Zend\Loader\StandardAutoloader' => array(
                      'namespaces' => array(
      		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                          __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                      ),
                  ),
              );
          }
      
          public function getConfig()
          {
              return include __DIR__ . '/config/module.config.php';
          }
      .............
      
  43. percynguyen92 said, on February 20, 2013 at 11:40 am

    i can’t understand this row, where is “flashmessenger()”, i can’t find it in AbstractController

    ‘messages’ => $this->flashmessenger()->getMessages()

    • samsonasik said, on February 20, 2013 at 3:03 pm

      it call controller plugin which automatically invoked via PluginManager, see : Zend\Mvc\Controller\PluginManager in $invokableClasses value.

  44. percynguyen92 said, on February 20, 2013 at 2:22 pm

    one more question

    in this code

    if ($result->isValid())
    {
    $redirect = ‘cpanel’;
    //check if it has rememberMe :
    if ($request->getPost(‘rememberme’) == 1 )
    {
    $this->getSessionStorage()->setRememberMe(1);
    //set storage again
    $this->getAuthService()->setStorage($this->getSessionStorage());
    }
    $this->getAuthService()->getStorage()->write($request->getPost(‘username’));
    }

    why must set storage again? and why not call method $this->getSessionStorage()->write()?

  45. Dinesh Kumar Sahoo said, on February 23, 2013 at 3:41 pm

    Hi Samsonasi,

    We are using “AuthService” as one of our factories in Module.php file. You, might have seen the album listing, edit, delete tutorial. Using the same code I want to insert data into the database (add user). But I am not able to. Can you please mention the places which will require modifications ? (along with code please).

    This will be a fantastic tutorial if you provide some code to save session data in our database.

    But, the first one is a priority for me I am stuck.

    Thanks, in advance.

  46. zirtrex said, on February 26, 2013 at 3:57 am

    Hi i has written your tutorial , but I has recived this error:
    Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in C:\xampp\htdocs\control\vendor\ZF2\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42
    I like me, that you say me why?

  47. zirtrex said, on February 26, 2013 at 4:58 am

    hi! I read it yet, say me, where put the folder that i download, it your name is : DoctrineCommon.
    I download of http://docs.doctrine-project.org/

    • samsonasik said, on February 26, 2013 at 5:01 am

      you should install by composer, so it automatically downloaded to vendor folder and automatically added to autoload

  48. zirtrex said, on February 26, 2013 at 5:20 am

    Ok thank, I’ m new in this the zend framework and i dont understand still, buy thanks.

  49. zirtrex said, on February 27, 2013 at 6:04 am

    Hi ! how do i do, for add more data the validation?, for example a keyword
    user: name1;
    pass: pass1;
    keyword: dog;

  50. zirtrex said, on February 27, 2013 at 6:38 am

    other query, how recovery the data of my tabla, for example the id?, I in my tabla have id_user, user, pass;
    I want recover id_user for it use in a query a my database

  51. Délano de Rooij (@syrast) said, on February 27, 2013 at 10:38 pm

    Hi Samsonasik,

    First of all, a wonderful tutorial! I’ve learned a lot!
    I took me a while to get the Doctrine working, but thanks to your other tutorial it’s all working fine now.

    My only question is (and note: i’m still a ZF2-noobie) is there anyway to include this auth-check in every page without pasting it into the indexController?

    I tried using pasting this piece of code into the constructor of my page

    public function __construct()
    {
    if (! $this->getServiceLocator()
    ->get(‘AuthService’)->hasIdentity()){
    return $this->redirect()->toRoute(‘login’);
    }
    }

    But now i get the following error ” Fatal error: Call to a member function get() on a non-object in C:\xampp\htdocs\zf2-tutorial\module\Album\src\Album\Controller\AlbumController.php on line 16 ”

    Thanks in advance,
    Delano

  52. Ori said, on March 4, 2013 at 5:49 pm

    This is great learning. Have you used ZfcUser? You could teach us how to use and expand it.

  53. vita said, on March 6, 2013 at 2:54 pm

    How to get if user is logged in view like in zf1 zend_auth

    • vita said, on March 6, 2013 at 3:50 pm

      ok, thanks, i didn’t found it

  54. seethal said, on March 7, 2013 at 5:32 pm

    here the username is not checked for case sensitivity. how can we check username is valid

  55. jk2001 said, on March 11, 2013 at 9:50 am

    This has been very instructive. Thank you for writing it. I was wondering why, on line 90 of AuthController, you set the storage again:

    $this->getAuthService()->setStorage($this->getSessionStorage());

    • samsonasik said, on March 11, 2013 at 4:28 pm

      because current storage (default) doesn’t have rememberme functionality, so we re-set again 😉

      • jk2001 said, on March 11, 2013 at 5:38 pm

        I thought it was set up in line 32 of Module.php.

        I think I’m not understanding the router.

  56. Mohammad Nomaan Patel said, on March 14, 2013 at 11:35 am

    Sir how to get the id of logged in user. This id will be used in other table as foreign keys…
    Thanks in advance

    • samsonasik said, on March 14, 2013 at 12:22 pm

      try :

      print_r($this->getAuthService()->getAdapter()->getResultRowObject());
      
  57. Mohammad Nomaan said, on March 15, 2013 at 11:05 am

    it returning the username of logged in user instead of id..

    • samsonasik said, on March 15, 2013 at 1:36 pm

      you can get that after authenticate() process.

      $this->getAuthService()->getAdapter()
                             ->setIdentity($request->getPost('username'))
                             ->setCredential($request->getPost('password'));
                             
      $result = $this->getAuthService()->authenticate();
      
      $result = $this->getAuthService()->getAdapter()->getResultRowObject();
      $usersrow  = $this->getUserTable()->getUserById($result->id);
      

      after getting the ‘id’, you should save to the session :

      $this->getAuthService()->getStorage()->write(array(
                     'id' => $result->id,
                     'username' => $result->username,
                    //other session key => value here.
      ));
      

      and, you can get it in another resource like the following :

      if ($this->getServiceLocator()->get('AuthService')->hasIdentity()) {
          $users = $this->getServiceLocator()->get('SanAuth\Model\AuthStorage')->read();
          echo $users['id'];
      
          print_r($users);
      }
      
      • Mohammad Nomaan Patel said, on March 15, 2013 at 2:07 pm

        Thanks for the reply..
        I have tried but it is still giving the first character of username and giving a warning “Warning: Illegal string offset ‘id’ “…
        Regards

      • samsonasik said, on March 15, 2013 at 2:09 pm

        you should check the column name from the db.

  58. Ivan Jiménez (@i_morgado) said, on March 17, 2013 at 2:32 pm

    Very good work man….thank you!!!!

  59. Samia said, on March 18, 2013 at 10:34 pm

    Hi. Thats really good work. I am following ur tutorial but using zend form to create the form that develops login page. When i try to login its giving me follwing exception : The supplied parameters to DbTable failed to produce a valid sql statement, please check table and column names for validity.

    • samsonasik said, on March 19, 2013 at 5:58 am

      check your zf version, use latest version ( 2.1.3). the exception introduce in zf 2.1.0

  60. kathir said, on March 19, 2013 at 8:59 am

    Hi I get an error when i click on the submit button

    /auth/authenticate was not found on this server. I have just downloaded the code from your git repo and added to my skeleton application.

    • samsonasik said, on March 19, 2013 at 1:18 pm

      I think it’s your server problem. please see apache error log. and see if your httpd.conf already setting up properly.

      • kathirsurya said, on March 19, 2013 at 1:25 pm

        I have already checked the server conf. Snd it looks ok. I can see the login form from your sample code. But when click on the submit button, it does nt work. For some reason its not able to find the Auth controller authenticate method . Could it be route issue?

      • samsonasik said, on March 19, 2013 at 1:28 pm

        if the error is : “A 404 error occurred” I think it’s route issue, but if the error is “The requested /auth/authenticate was not found on this server.” , it’s your apache or directory path problem.

  61. Kamy said, on March 19, 2013 at 8:02 pm

    Thank you very much for this, it was of great help!

  62. Jamie Mclaughlan said, on April 5, 2013 at 6:11 am

    Hi samsokasik, I ventured onto the zend community website earlier and saw that you were a very active user, which I think is great :).

    Anyway, I have an issue with the storage part. I’m testing using PHPUnit and an error occurs stating that:

    “session_regenerate_id(): cannot regenerate sessionId – headers already sent.”

    This is to do with the logoutAction within the controller. Any help would be great.

    Thank you!

    • Jamie Mclaughlan said, on April 5, 2013 at 6:22 am

      Sorry for my misspelling of your name samsonasik, I was rushing haha. Thanks again

  63. samsonasik said, on April 5, 2013 at 6:33 am

    try add :

    ob_start() ;
    

    at the end of Bootstrap.php

    • Jamie Mclaughlan said, on April 5, 2013 at 10:10 am

      great little fix, and a fantastic tutorial, especially for beginners like myself.

      1 last question, how would change the error messages of the Authentication to something more easily readible?

      • samsonasik said, on April 5, 2013 at 1:12 pm

        create a class that extends Zend\Authentication\Adapter\DbTable and override _authenticateValidateResultSet() and _authenticateValidateResult() function and use at adapter for your AuthenticationService.

    • chirag said, on February 1, 2014 at 5:21 pm

      I have user zf2 I got error like this: “session_regenerate_id(): cannot regenerate sessionId – headers already sent.”

      This is to do with the logoutAction within the controller.
      There is no bootstrap.php file

      Any help would be great.

      Thanks,

      • samsonasik said, on February 2, 2014 at 3:55 pm

        you must be have whitespace somewhere, find it or fix them using php-cs-fixer.

  64. sandeshsm said, on April 9, 2013 at 2:54 pm

    I have installed this module on my local xampp server.

    I am getting following error:

    Fatal error: Uncaught exception ‘Zend\ServiceManager\Exception\InvalidArgumentException’ with message ‘Provided abstract factory must be the class name of an abstract factory or an instance of an AbstractFactoryInterface.’ in C:\Projects\zf2latest\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php on line 260
    ( ! ) Zend\ServiceManager\Exception\InvalidArgumentException: Provided abstract factory must be the class name of an abstract factory or an instance of an AbstractFactoryInterface. in C:\Projects\zf2latest\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php on line 260
    Call Stack
    # Time Memory Function Location
    1 0.0124 149480 {main}( ) ..\index.php:0
    2 0.2764 269248 Zend\Mvc\Application::init( ) ..\index.php:15
    3 0.8805 1067408 Zend\ModuleManager\ModuleManager->loadModules( ) ..\Application.php:238
    4 1.4672 1444816 Zend\EventManager\EventManager->trigger( ) ..\ModuleManager.php:108
    5 1.4672 1444856 Zend\EventManager\EventManager->triggerListeners( ) ..\EventManager.php:204
    6 1.4673 1446064 call_user_func ( ) ..\EventManager.php:460
    7 1.4673 1446080 Zend\ModuleManager\Listener\ServiceListener->onLoadModulesPost( ) ..\EventManager.php:460
    8 1.4725 1470912 Zend\ServiceManager\Config->configureServiceManager( ) ..\ServiceListener.php:223
    9 1.4734 1484208 Zend\ServiceManager\ServiceManager->setFactory( ) ..\Config.php:122

    Can you please help me in this regard?

    Thanks in advance!

    Regards
    Sandesh Magdum

  65. Mohammad Nomaan Patel said, on April 15, 2013 at 7:54 pm

    Hi..

    I want to show the messages, if a user enters a wrong details without refreshing the login page. I have tried some ajax code on form submit as

    $(document).ready(function(){
    $(‘form’).submit(function(){
    var sendData=$(this).serialize();
    alert(sendData);
    $.ajax(
    {
    url:’auth’,
    dataType:’json’,
    type:’POST’,
    data:sendData,

    error:function(data)
    {

    },
    success: function(data) {
    }

    });

    return false;
    });
    });

    Can you give suggestion for this.

    Thanks

  66. Musafar said, on April 16, 2013 at 3:31 pm

    (sorry for the mistake in your name… I just saw the real spelling now)

  67. Phuc said, on April 17, 2013 at 8:29 pm

    When I try on localhost: http://localhost/LVTN/public/home/auth/login

    Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in D:\wamp\www\LVTN\TK\Zf2Demo\vendor\zendframework\zendframework\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42

    I think it is error: Add doctrine/common to composer.json
    Can you help me ! thank

  68. saadaoui seifeddine said, on April 18, 2013 at 10:30 pm

    hello! thnks a lot for the code! i just want to know, where you have specified the database ? thnks in advance 🙂

  69. Muhammad Amjad said, on April 21, 2013 at 2:15 pm

    Salam Bro
    very nice tutorial but i got error on authentication : The supplied parameters to DbTable failed to produce a valid sql statement, please check table and column names for validity.

    • samsonasik said, on April 21, 2013 at 6:44 pm

      salam…
      use latest zf version.

      • Muhammad Amjad said, on April 22, 2013 at 12:08 am

        wasalam
        i am using latest version i was using mistakenly two files for database connectivity now problem resolved thanks for response.

      • samsonasik said, on April 22, 2013 at 10:51 am

        you’re welcome 😉

  70. Musafar said, on April 23, 2013 at 8:38 pm

    Assalamu alaikkum bro,
    I used ‘Zend\Crypt\Password\Bcrypt’ to encrypt the passwords and then stored in db.
    Then in ServiceManager, I used:

    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, ‘users’, ‘username’, ‘password’, ‘PASSWORD(?)’);

    But it isn’t working. I used MD5 and it is working fine. So I think the problem is with Bcrypt encryption. Here is the code where encryption take place: http://pastebin.com/UPvR9Eqy

    Thanks in advance 😀

    PS: I am using Zend/Form

    • samsonasik said, on April 24, 2013 at 5:44 am

      if you’re using bcrypt, you should setSalt first to make it not re-generated every it called.

      $bcrypt->setSalt('vlAzj20g2e7.x8s3sm5dLbLkFOw.Qa');
      

      you can’t use that in constructor of DbTableAuthAdapter, use at setCredential function.

      use Zend\Crypt\Password\Bcrypt;
      $bcrypt = new Bcrypt();
      $bcrypt->setSalt('vlAzj20g2e7.x8s3sm5dLbLkFOw.Qa');
      $securedpassword = $bcrypt->create($request->getPost('password'));
       
      $this->getAuthService()->getAdapter()
             ->setIdentity($request->getPost('user'))
             ->setCredential($securedpassword);
      
      • Musafar said, on April 25, 2013 at 1:29 pm

        I dint understand. I dint add password ‘value’ in the constructor. I added the db field names (as mentioned in the docs).

        What I understood from your code is:
        We need to specify the encrypted password as the credential; and we don’t need to provide ‘PASSWORD(?)’ in the constructor. And if so, Zend\Authenticate. Why can’t we use Zend\Crypt\Password\Bcrypt alone?

        Please correct me! 🙂

        And how can I add those syntax highlighting for codes in comments?

      • samsonasik said, on April 25, 2013 at 4:07 pm

        $credentialTreatment is database centrict (PASSWORD, MD5, Sha1, whatever) which Bcrypt is NOT. if you want to use other encryption way, you should leave it empty as :

        $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, ‘users’, ‘username’, ‘password’);
        

        and use encrypted password to setCredential() function.

        read the codex to post sourcecode http://en.support.wordpress.com/code/posting-source-code/

      • Musafar said, on April 25, 2013 at 5:31 pm

        ok tyvm… although I dint understand you completely I got it working.. 😉

      • Musafar said, on April 25, 2013 at 6:35 pm

        one more thing: can I get other values from db without fetching them manually?
        like:

        Zend\Authentication\Adapter\DbTable::getResultRowObject('fieldName');
      • samsonasik said, on April 25, 2013 at 6:48 pm

        assign that to variable :

        $result = $this->getAuthService()->getAdapter()->getResultRowObject();
        
        echo $result->id;
        echo $result->username;
        echo $result->pass_word;
        //etc...
        
      • Musafar said, on April 25, 2013 at 7:18 pm

        I am trying to get the data in Application’s IndexController

        var_dump($this->getAuthService()->getIdentity());

        output: string(7) “musafar”

        but, echo’ing throws “property of non-object” error and

        $result = $this->getAuthService()->getAdapter()->getResultRowObject();
        var_dump($result);

        output: bool(false)

      • samsonasik said, on April 25, 2013 at 7:25 pm

        use that at authenticate process only.

      • Musafar said, on April 25, 2013 at 7:30 pm

        ok, I thought we are using a Session

      • Musafar said, on April 25, 2013 at 7:42 pm

        ok I got what I want

        $res = $this->getAuthService()->getAdapter()->getResultRowObject();
                			$this->getAuthService()->getStorage()->write(array(
                				$request->getPost('username'), $res->fieldName
                			));

        Thanks for your help and thanks for such posts 🙂

  71. Srikanth Kalyan said, on April 24, 2013 at 1:15 pm

    Hi sam,

    actually I am looking for creating a admin and user system where both has to LOGIN to access the pages.
    for this I used ‘zfcuser’ and ‘bjyauthorize’ where I can gaurd the routes and controllers.

    Up to that I am fine.

    but when I LOGIN to system it is redirecting to same INDEX page of ‘zfcuser’ for both ADMIN and USER.

    but I want to redirect to separate pages for ADMIN and USER which is not happening by default.

    Please advice me a best solution for this to work.

    It will be great if I get any help.

    Thanks in advance.

    • samsonasik said, on April 24, 2013 at 6:11 pm

      try something like this :

              $authidentityproviderRole = $this->getServiceLocator()
                      ->get('BjyAuthorize\Provider\Identity\AuthenticationIdentityProvider')
                      ->getAuthenticatedRole();
              if ($authidentityproviderRole == 'admin') {
                  //redirect to admin...
              }
      
      • Ben said, on June 4, 2014 at 8:23 pm

        If you are using ‘Zend\Authentication\AuthenticationService’ in Module.php this will not work with the BjyAuthorize Module roles and ACL. BjyAuthorize will default to its own default configuration of the AuthenticationService which uses ‘ZfcUser\Authentication\Storage\Db’. To get BjyAuthorize to use the Doctrine stored identity, add ‘zfcuser_auth_service’ to the factories section as follows:

        public function getServiceConfig()
        {
        return array(
        ‘factories’ => array(
        ‘zfcuser_auth_service’ => function ($serviceManager) {
        return $authenticationService = $serviceManager->get(‘doctrine.authenticationservice.orm_default’);
        },
        )
        );
        }

        You can use it in the controller as follows:

        $authService = $this->getServiceLocator()->get( ‘zfcuser_auth_service’ );

      • Ben said, on June 4, 2014 at 8:30 pm

        Sorry, I should have pointed out that my post applies if you are using Doctrine to persist identity

  72. Srikanth Kalyan said, on April 24, 2013 at 6:21 pm

    I should give this in authenticate Method of the UserController sam??

  73. Srikanth Kalyan said, on April 24, 2013 at 6:42 pm

    okay cool sam, But may I know is there any other alternative way to achieve it? without using bjyauthorize?

  74. Srikanth Kalyan said, on April 24, 2013 at 8:34 pm

    any idea to share that in coming future?? if so it would be very happy for all who is looking for this!!
    anyways Thank you so much for being so kind!

  75. anji said, on May 6, 2013 at 10:32 am

    Fatal error: Uncaught exception ‘Zend\ModuleManager\Listener\Exception\InvalidArgumentException’ with message ‘Config being merged must be an array, implement the Traversable interface, or be an instance of Zend\Config\Config. NULL given.’ in C:\xampp\htdocs\Anji\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\ConfigListener.php:324 Stack trace: #0 C:\xampp\htdocs\Anji\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\ConfigListener.php(130): Zend\ModuleManager\Listener\ConfigListener->addConfig(‘SanAuth’, NULL) #1 [internal function]: Zend\ModuleManager\Listener\ConfigListener->onLoadModule(Object(Zend\ModuleManager\ModuleEvent)) #2 C:\xampp\htdocs\Anji\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(460): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent)) #3 C:\xampp\htdocs\Anji\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(204): Zend\EventManager\EventManager->triggerListeners(‘loadModule’, Object(Zend\M in C:\xampp\htdocs\Anji\vendor\zendframework\zendframework\library\Zend\ModuleManager\Listener\ConfigListener.php on line 324

    • anji said, on May 6, 2013 at 10:36 am

      as early as possible please resolve the above issue

      • samsonasik said, on May 6, 2013 at 11:13 am

        in Module.php, fill following functions with /*common code*/ functions of Module class.

        //module/SanAuth/Module.php
        .............
            public function getAutoloaderConfig()
            {
                return array(
                    'Zend\Loader\ClassMapAutoloader' => array(
                        __DIR__ . '/autoload_classmap.php',
                    ),
                    'Zend\Loader\StandardAutoloader' => array(
                        'namespaces' => array(
                    // if we're in a namespace deeper than one level we need to fix the \ in the path
                            __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                        ),
                    ),
                );
            }
         
            public function getConfig()
            {
                return include __DIR__ . '/config/module.config.php';
            }
        .............
        

        btw, download complete example in http://github.com/samsonasik/SanAuth

  76. saadaoui seifeddine said, on May 6, 2013 at 4:19 pm

    good morning, thnks for the good job samsonasik, but i want to ask if that you have used the authentication service?? because i didn”t find
    use Zend\Authentication,
    Zend\Authentication\Result;

    and
    then after creating this authentication , in the layout of my application , i want to get the identity of the logged in user, how to get it??
    thank you in advance 🙂

  77. saadaoui seifeddine said, on May 6, 2013 at 8:38 pm

    i’ve read it, ! and i tryed to make it on my view helper but , it shows an error : Fatal error: Call to undefined method Annonceur\View\Helper\getidentity::identity() in C:\wamp\www\zf2\module\Annonceur\src\Annonceur\View\Helper\getidentity.php on line 16
    donnow why? O.o

    • samsonasik said, on May 6, 2013 at 9:04 pm

      if you call from view_helper, you should call by

      $this->view->plugin('identity');
      
      • saadaoui seifeddine said, on May 6, 2013 at 9:13 pm

        thank you so much 🙂 and how to get the identity from it??

  78. Mohammad Nomaan said, on May 8, 2013 at 8:00 pm

    Hi,
    While using bcrypt instead of md5, I want to pass salt to it.

    My question is can we pass random salt string to bcrypt..

    Thanks

    • samsonasik said, on May 9, 2013 at 9:16 pm

      if you save passwords, you should have concensus of salt.

      • Mohammad Nomaan said, on May 11, 2013 at 3:35 pm

        ok thanks

      • samsonasik said, on May 12, 2013 at 4:54 am

        You’re welcome 🙂

  79. amine said, on May 12, 2013 at 5:52 pm

    Fatal error: Uncaught exception ‘Zend\Mvc\Router\Exception\RuntimeException’ with message ‘Route with name “SanAuth” not found’ in C:\wamp\www\Zend2\vendor\zendframework\zendframework\library\Zend\Mvc\Router\Http\TreeRouteStack.php on line 187

  80. ZeinEddin said, on May 14, 2013 at 8:26 pm

    Alsalam Alaikom:
    This was a very useful tutorial, I learned a lot from it, but can you please help me with this question:
    http://stackoverflow.com/questions/16497449/zfcrbac-can-not-get-identity-from-an-mvc-event

  81. Hajar said, on May 15, 2013 at 4:00 pm

    Assalam Alaikom :
    I have tried to run you’re exemple in my aplication and i have this error .I don’t no how to deal with it, i ‘m just a beginer:

    Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in C:\wamp\www\zf2\vendor\zendframework\zendframework\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42

    Thank you

    • Hajar said, on May 15, 2013 at 4:20 pm

      Assal Alaikom Don’t buther you’re self with my probleme. I did find the solution : i did forget to add
      “doctrine/common” : “>=2.1” to my composer.json
      Thank you for this amazing tutorial

  82. Carlos RGarcia said, on June 9, 2013 at 1:09 am

    Hello thank you for sharing your knownledge 🙂 I have learned so much with your blog, I am trying to store user objects with the session,not stdClass, so I have to serialize when I want to write to session and unserialize when I want to get the object, but I get this error:

    PHP Notice: Auth\\Controller\\AccountController::personalAction(): The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Auth\\Model\\UsersInSession; of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition

    Here is my code:

    session->{$this->member};
    $obj = $serializer->unserialize($string);
    return $obj;
    }
    public function write($contents)
    {
    error_log(‘Ejecutando’ . __METHOD__);
    $serializer = \Zend\Serializer\Serializer::factory(‘phpserialize’);
    $serialized = $serializer->serialize($contents);
    $this->session->{$this->member} = $serialized;
    }
    public function setRememberMe($rememberMe = 1, $time = 1209600)
    {
    error_log(‘Ejecutando’ . __METHOD__);
    if ($rememberMe == 1) {
    $this->session->getManager()->rememberMe($time);
    }
    }

    public function forgetMe()
    {
    error_log(‘Ejecutando’ . __METHOD__);
    $this->session->getManager()->forgetMe();
    }

    }

    getAdapter()) {
    throw new Exception\RuntimeException(‘An adapter must be set or passed prior to calling authenticate()’);
    }
    }
    $result = $adapter->authenticate();
    $resultSet = $adapter->getResult();

    if ($this->hasIdentity()) {
    $this->clearIdentity();
    }
    if ($result->isValid()) {
    $resource = $resultSet->getResource();
    $serializer = \Zend\Serializer\Serializer::factory(‘phpserialize’);
    $object=$resource->fetchObject(‘Auth\Model\UsersInSession’);
    $this->getStorage()->write($object);
    error_log(‘_SESSION: ‘.print_r($_SESSION,1));
    }

    return $result;
    }
    public function getLogged()
    {
    error_log(‘Ejecutando: ‘ . __METHOD__);
    if(!$this->logged){
    if($this->hasIdentity()){
    $this->logged = $this->getStorage()->read();
    }
    }
    return $this->logged;
    }
    }
    And in the controller, when I want to get the object I do this:
    $logged = $this->getAuthService()->getStorage()->read();
    error_log(‘user: ‘ . $logged->name);

    I know that I can fix it executing a include(‘folder-to-the-class-UsersInSession.php’);

    But I would like to solve it with a more elegant way,do you know how could I solve it?
    Thanks 🙂

  83. Muhammad Amjad said, on June 9, 2013 at 2:11 pm

    Salam brother
    I dont have idea how to make override a module i have searched and tried a lot to make module override but failed i you have time please post a tutorial for it…
    Thanks

    • samsonasik said, on June 10, 2013 at 9:42 pm

      override module ? override service maybe :). override your service with allow_override option at your service manager registration.

  84. Fran said, on June 10, 2013 at 4:22 am

    If anybody interested on registration/login form for ZF2 https://github.com/xFran/TarSignup

  85. conceptdeluxe said, on June 11, 2013 at 9:00 am

    As already asked/stated by other commentators…

    In general it is not(!) necessary to set the AuthStorage again once it is set in the factory. You can easily verify this by watching the class instance while debugging. Although I am not running your module as is, my test environment was more or less based on your approach.

    Beside that, big thanks for your blog – it is a substantial resource for learning about zf2 🙂

  86. How To Create A Blog said, on June 13, 2013 at 9:18 am

    If you want to take a great deal from this piece of writing then you have
    to apply these methods to your won webpage.

  87. zirtrex said, on June 13, 2013 at 8:59 pm

    how to do the same, but using form in layout?
    Send me an example please.
    I have implemented a lot of the code in a view helper but when i need send the form; can´t recive the data,

    class FormHelper extends AbstractHelper implements ServiceLocatorAwareInterface
    {
    protected $form;
    protected $authService;
    protected $request;

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
    {
    $this->serviceLocator = $serviceLocator;
    return $this;
    }

    public function getServiceLocator()
    {
    return $this->serviceLocator;
    }

    public function getAuthService()
    {
    if(! $this->authService){
    $this->authService = $this->getServiceLocator()->getServiceLocator()->get(‘AuthService’);
    }

    return $this->authService;
    }

    public function getForm()
    {
    if(! $this->form){
    $usuario = new Usuarios();
    $builder = new AnnotationBuilder();
    $this->form = $builder->createForm($usuario);
    }

    return $this->form;
    }

    public function autentificacion()
    {
    $form = $this->getForm();

    $this->request = new Request();
    $dev = var_dump($this->request);//->isPost();
    /*if ($this->request->isPost()){

    $form->setData($this->request->getPost());

    if ($form->isValid()){

    $this->getAuthService()->getAdapter()
    ->setIdentity($this->request->getPost(‘usuario’))
    ->setCredential($this->request->getPost(‘contrasenia’));

    $result = $this->getAuthService()->authenticate();

    if ($result->isValid()) {

    $this->getAuthService()->getStorage()->write($this->request->getPost(‘usuario’));

    return array(
    ‘mensajes’ => ‘Bienvenido ‘ . $this->getAuthService()->getIdentity()
    );

    }

    }
    }*/

    return array(
    ‘mensajes’ => ‘de nuevo’ . $dev
    );
    }

    public function __invoke()
    {

    $var = $this->autentificacion();

    if($this->getAuthService()->hasIdentity()){
    return array(
    “login” => “ya iniciaste sesion”,
    );
    }else{

    }
    $form = $this->getForm();

    $identidad = $this->getAuthService()->getIdentity();

    return array(
    “form” => $form,
    “identidad” => $identidad,
    “mensajes” => $var[“mensajes”],
    );

    Request isn´t the object i was waitting for;result is:

    object(Zend\Http\Request)#308 (9) { [“method”:protected]=> string(3) “GET” [“uri”:protected]=> NULL [“queryParams”:protected]=> NULL [“postParams”:protected]=> NULL [“fileParams”:protected]=> NULL [“version”:protected]=> string(3) “1.1” [“headers”:protected]=> NULL [“metadata”:protected]=> array(0) { } [“content”:protected]=> string(0) “” }

    I don´t get the method:
    isPost();

    What should i need to do to this work?.

  88. Dinesh Sahoo said, on June 19, 2013 at 7:48 pm

    The client side validations added for the Login form is not working in Internet explorer. Please comment or suggest for its alternative.

  89. Vimal raj said, on July 2, 2013 at 10:59 pm

    You are my Guru

  90. Alistair said, on July 3, 2013 at 2:10 pm

    Hey hi, its Alistair. Thanks for the tutorial 🙂
    but i am unable to understand given statement i m not getting it , can you please explain me ?
    $this->authservice = $this->getServiceLocator()->get(‘AuthService’);

  91. Mohammad Nomaan said, on July 11, 2013 at 5:36 pm

    Hi….
    I need some help regarding validation of username while registering user. While registering username should not take space. How it could be done???

  92. nomaanp153 said, on July 25, 2013 at 1:44 pm

    Hi Samsonasik,
    I am facing problem with logout action. Suppose there are two application named App1 and App2. Both the applications are containing the same login module ie ‘SanAuth’ and both the applications are running simultaneously in the same browser. If I login in to the App1 application, I automatically get logged in to App2. This is due to the same storage name in SanAuth’s Module.php . You can look it here

    By changing the name of one of the application’s storage, this problem is solved.

    The problem is with the logout action. If I logout from App1, the session storage of App2 would automatically get cleared, though the session storage’s name are different. I searched for this problem in zf2 docs, but there is no luck.

    • samsonasik said, on July 25, 2013 at 2:23 pm

      Try :
      $this->getAuthService()->getStorage()->clear();

      • nomaanp153 said, on July 25, 2013 at 3:04 pm

        Thanks for the reply!!!
        Little bit changes solved it.

        $storage_name = $this->getAuthService()->getStorage()->getNamespace();

        $this->getAuthService()->getStorage()->clear($storage_name);

      • samsonasik said, on July 25, 2013 at 3:45 pm

        Excellent, great!

  93. MohamedAli said, on July 25, 2013 at 11:03 pm

    Salam brother

    thx alot for you’r tutorial and you’r Authentification Model , it works fine i add some elements on the database like “role” . I’m aking how can i use the “username” or the “role” any other parameter of an authentificated user , to test on other function on my application .

    Thx

    • samsonasik said, on July 26, 2013 at 6:07 am

      $this->getAuthService()->getStorage()->read();

      • MohamedAli said, on July 26, 2013 at 7:47 pm

        Thanx Sam i really appreciate you’r work on this blog

        like i told you i add the field “role” on the data base and i whant to make some test with , like {if($role == ‘Admin’) redirect rout’X’} else redirect to rout’Y’

        but when i use this

        if ($this->getServiceLocator()->get(‘AuthService’)->hasIdentity()) {
        $users = $this->getServiceLocator()->get(‘AuthService’)->getStorage()->read();
        echo $users[‘role’];
        }

        i recieve this error ” Notice: Undefined index: role in /home/ali/Bureau/zend/bf/module/SanAuthWithDbSaveHandler/src/SanAuthWithDbSaveHandler/Controller/AuthController.php”

        but when i use the username for test

        if ($this->getServiceLocator()->get(‘AuthService’)->hasIdentity()) {
        $users = $this->getServiceLocator()->get(‘AuthService’)->getStorage()->read();
        echo $users[‘username’];
        }

        all worck fine

        Any help plz

      • samsonasik said, on July 26, 2013 at 7:57 pm

        then you need to write the session value properly, print_r the data and break execution ( die; ) before write ->getStorage()->write($data);

      • MohamedAli said, on July 26, 2013 at 8:10 pm

        Sorry i didn’t understand you’r solution can you get me the all function

    • MohamedAli said, on July 26, 2013 at 8:49 pm

      What’s the difference between this modul and the “Working with AuthenticationService and Session Db Save Handler ” Module ???

      https://samsonasik.wordpress.com/2013/05/29/zend-framework-2-working-with-authenticationservice-and-db-session-save-handler/

      for my issue what do you suggest me to use ??

  94. Emf said, on July 29, 2013 at 8:01 pm

    How to redirect to the previous page (url) after login ?

    • samsonasik said, on July 29, 2013 at 8:12 pm

      1. bring your previous page as $_GET parameter, then you can get something like /auth/login?continue=contactus
      2. make a page like /contactus forwardable to loginpage, the url like /contactus, but the content is login page. 😉

  95. Mohammad Nomaan said, on August 8, 2013 at 11:57 am

    Hi Samsonasik,

    I am facing a problem regarding deploying a site on linux shared server. My problem is that after authentication, it should be redirected to another page. It stops on the route ‘http://www.example.com/auth/authenticate’. The user gets authenticated but it doesn’t redirect to other page.

    • samsonasik said, on August 8, 2013 at 7:57 pm

      try

      ob_start();
      header("Location:/success");
      

      i’m not on my front of pc right now, but hope inspire ^^

      • Mohammad Nomaan said, on August 12, 2013 at 3:59 pm

        Thanks for your reply. It is giving this error
        Cannot modify header information – headers already sent by and not getting redirected.

        btw Eid Mubarak!!!!

      • samsonasik said, on August 12, 2013 at 8:02 pm

        it seems your php files not trimmed ( white space(s) ), try php-cs-fixer to fix them. thanks, happy ied mubarok to you too 🙂

      • Mohammad Nomaan said, on August 13, 2013 at 1:12 pm

        used php cs-fixer but no luck!!!

      • Mohammad Nomaan said, on August 13, 2013 at 2:16 pm

        PHP version for my server is 5.3.23. Can php version would be the problem????

      • samsonasik said, on August 13, 2013 at 7:27 pm

        i think you should check your apache error log, and see what happen…

      • nomaanp153 said, on August 16, 2013 at 12:05 pm

        Hi, It was server problem. According to you, which type of server would be suitable for Zend Framework applications.

  96. Hans-Peter said, on August 13, 2013 at 4:38 pm

    Thanks for the great tutorial. I would like to provide the album modul with a login. How can i use the san-auth modul for login of the album module? I’am a newbie and need detailed instructions. many thanks.

  97. ram said, on August 16, 2013 at 2:16 pm

    hi its really good work

    really helpful for new learners.

    please help me for creating database connection and in src/model/…php folder

  98. ram said, on August 22, 2013 at 4:13 pm

    hi
    i want the procedure for creating contact form in zend one of the module.
    already in that one registration page is created now i have to create contact us form in another page in same module.

    please tell the procedure…

    thanks

  99. bhuvanesh said, on August 26, 2013 at 3:19 pm

    Connect Error: SQLSTATE[HY000] [1044] Access denied for user ”@’localhost’ to database ‘smb’

  100. bhuvanesh said, on August 26, 2013 at 3:20 pm

    i have connect with database but i m getting this error

  101. bhuvanesh said, on August 26, 2013 at 3:44 pm

    global.php

    return array(
    ‘db’ => array(
    ‘driver’ => ‘Pdo’,
    ‘dsn’ => ‘mysql:dbname=smb;host=localhost’,
    ‘driver_options’ => array(
    PDO::MYSQL_ATTR_INIT_COMMAND => ‘SET NAMES \’UTF8\”
    ),
    ),
    ‘service_manager’ => array(
    ‘factories’ => array(
    //’Blog\Model\MyAuthStorage’=>’smb’,
    ‘Zend\Db\Adapter\Adapter’
    => ‘Zend\Db\Adapter\AdapterServiceFactory’,
    ),
    ),
    // …
    );

    local.php

    return array(
    ‘doctrine’ => array(
    ‘connection’ => array(
    ‘orm_default’ => array(
    ‘driverClass’ => ‘Doctrine\DBAL\Driver\PDOMySql\Driver’,
    ‘params’ => array(
    ‘host’ => ‘localhost’,
    ‘port’ => ‘3306’,
    ‘user’ => ‘msphere’,
    ‘password’ => ‘msphere’,
    ‘dbname’ => ‘smb’,
    )
    )
    )
    ),
    );

    my all other application running successfully….
    my login page uername and password alone displaying but when i m clicking submit, im getting this error
    Connect Error: SQLSTATE[HY000] [1044] Access denied for user ”@’localhost’ to database ‘smb’….

    one more thing i put ur source code only…

  102. bhuvanesh said, on August 26, 2013 at 4:18 pm

    ERROR CLEARED

    but username and password are not storing in users table…

  103. bhuvanesh said, on August 26, 2013 at 4:24 pm

    i m waiting for ur idea…

  104. bhuvanesh said, on August 26, 2013 at 4:27 pm

    Tell Me the best tutorial to learn zend framework2 and doctrine2

  105. bhuvanesh said, on August 26, 2013 at 7:48 pm

    when i entered the username correctly,its displaying like this
    *Supplied credential is invalid.

    when i entered some unwanted name,its displaying like this
    *A record with the supplied identity could not be found.

    • samsonasik said, on August 26, 2013 at 11:21 pm

      1st case : you enter wrong password
      2nd case : you enter wrong username.
      remember the hash of the password, i’m using md5, check the code !

  106. bhuvanesh said, on August 27, 2013 at 12:34 pm

    Thanks for ur explanation…I got the output

    my all other application I m using doctroine 2,,

    I want to use “login form” also doctroine2..can u send me any document to read or any other sample codings

  107. MohammedNizam said, on August 27, 2013 at 2:28 pm

    Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in D:\ampps\Ampps\www\MyZend\vendor\ZF2\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42
    i got this error ..i’m using ur SanAuth module …with sample skeleton Application,Album module.Album module it’s work fine but if i run sanAuth module i got the above error…

  108. Bharath said, on August 28, 2013 at 6:54 pm

    how to add 2 or more submit button in same form like save cancel and exit

    • samsonasik said, on August 29, 2013 at 4:09 pm

      create only one submit, and double/more echo with change setValue() on the fly, and then check on the valid form.

      $data = $form->getData();
      If ($data['submit'] =='save and continue') { 
          //do save and continue
      } 
      if ($data['submit'] == 'save') { 
          // do save only
      }
      
  109. Bharath said, on August 28, 2013 at 6:55 pm

    how to add 2 or more submit button in same form like save cancel and exit using ZF2 and doctrine2

    • bhuvanesh said, on August 29, 2013 at 4:45 pm

      for cancel u need to put ‘reset’,

      for exit u can use jquery…

  110. bhuvanesh said, on August 29, 2013 at 4:43 pm

    Near to logout,
    A username must pass from session….
    if new user entered his/her name pass from session…

    eg:like email,facebook etc….Give some ideas….even explain for me in codings

  111. Bharath said, on August 29, 2013 at 4:58 pm

    Access\Entity\Gradepst must have a “__toString()” method defined if you have not set a property or method to use.
    \

    How to solve this error using different table. 1st table as Gradetab another one is called Gradepst. The forign key as Gradepst_code as varchar

  112. Bharath said, on August 29, 2013 at 5:00 pm

    Thank you

  113. vasanthi said, on August 29, 2013 at 5:08 pm

    hi, I am using three buttons in form such that’s Save,Cancle,Exit if I am click the exit button then immediately go to exit. what I am do. my error is if I am click the exit button the save action is run. so help me.ia using zf2 and doctrine2.

  114. vasanthi said, on August 29, 2013 at 5:36 pm

    hi,pls help me I am using zf2 and doctrine2 concepts storing and retrieving data from database.my primary key type is “varchar”.so the add form have to text boxes one is enter code and another one is enter name.my problem is the textbox is get id value and stored it.it allowed white space also but I dn’t want space in adding id value.that produce problem to fitch the id value because it allowed white space.how to avoid the white space in entering time.how to use validation. pls give me any samples or solution.

    • samsonasik said, on August 30, 2013 at 1:09 am

      create your custom filter and apply to it.

      • vasanthi said, on September 5, 2013 at 3:13 pm

        thank you but i d n’t known custom filter how i am use my form give code for me. i am using module.config.php for id level is ‘designation’ => array(
        ‘type’ => ‘segment’,
        ‘options’ => array(
        ‘route’ => ‘/designation[/:action][/:id2]’,
        ‘constraints’ => array(
        ‘action’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
        ‘id’ => ‘[a-zA-Z0-9_-]*’, // i am using this type of id it get integers ,alphabet
        ),
        ‘defaults’ => array(
        ‘controller’ => ‘access/designation’,
        ‘action’ => ‘index’,
        ),
        ),
        ),

      • vasanthi said, on September 5, 2013 at 7:03 pm

        public function getInputFilter()
        {
        if (!$this->inputFilter) {
        $inputFilter = new InputFilter();
        $factory = new InputFactory();

        $inputFilter->add($factory->createInput(array(
        ‘name’ => ‘DEPT_CODE’,
        ‘required’ => true,
        ‘filters’ => array(
        array(‘name’ => ‘StripTags’),
        array(‘name’ => ‘StringTrim’),

        ),
        ‘validators’ => array(
        array(
        ‘name’ => ‘StringLength’,

        ‘options’ => array(
        ‘encoding’ => ‘UTF-8’,
        ‘min’ => 1,
        ‘max’ => 10,

        ),
        ),
        ),
        )));
        it take white space at entering time from form.i want avoid the white space at adding time from form how to implement this code help me.DEPT_CODE is primary key so “white space” is i dn’t want at storing time because that produe proble at fetch time.

      • samsonasik said, on September 5, 2013 at 7:18 pm

        create your own filter

  115. bhuvanesh said, on August 29, 2013 at 9:38 pm

    stdClass Object ( [id] => 2 [username] => bhuvi [password] => bhuvi ) stdClass Object ( [id] => 2 [username] => bhuvi [password] => bhuvi ) stdClass Object ( [id] => 2 [username] => bhuvi [password] => bhuvi )

    Messages:
    Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for getUserTable..

    I need username alone near to my logout..

  116. bhuvanesh said, on August 30, 2013 at 12:06 pm

    stdClass Object ( [id] => 2 [username] => bhuvi [password] => bhuvi )

    ( ! ) Fatal error: Call to undefined function Access\Controller\Username() in C:\wamp\www\bc2\module\Access\src\Access\Controller\AuthController.php on line 146

    Call Stack

    #

    Time

    Memory

    Function

    Location

    1 0.0008 144264 {main}( ) ..\index.php:0
    2 0.1250 4124616 Zend\Mvc\Application->run( ) ..\index.php:17
    3 0.1264 4145840 Zend\EventManager\EventManager->trigger( ) ..\Application.php:309
    4 0.1264 4145848 Zend\EventManager\EventManager->triggerListeners( ) ..\EventManager.php:207
    5 0.1265 4147056 call_user_func ( ) ..\EventManager.php:468
    6 0.1265 4147072 Zend\Mvc\DispatchListener->onDispatch( ) ..\EventManager.php:468
    7 0.1296 4254032 Zend\Mvc\Controller\AbstractController->dispatch( ) ..\DispatchListener.php:114
    8 0.1296 4254376 Zend\EventManager\EventManager->trigger( ) ..\AbstractController.php:117
    9 0.1296 4254376 Zend\EventManager\EventManager->triggerListeners( ) ..\EventManager.php:207
    10 0.1298 4261144 call_user_func ( ) ..\EventManager.php:468
    11 0.1298 4261160 Zend\Mvc\Controller\AbstractActionController->onDispatch( ) ..\EventManager.php:468
    12 0.1299 4261296 Access\Controller\AuthController->authenticateAction( ) ..\AbstractActionController.php:83

    codings;

    {
    $em = $this->getEntityManager();
    $form = $this->getForm();
    /*
    * $user_session = new Container(‘user’);
    * $username = $user_session->username;
    * $username = $_SESSION[‘user’][‘username’];
    */

    print_r($this->getAuthService()->getAdapter()->getResultRowObject());
    $redirect = ‘login’;

    $request = $this->getRequest();
    if ($request->isPost()){
    $form->setData($request->getPost());
    if ($form->isValid()){
    $em = $this->getEntityManager();
    // $this->escapeHtml($username);
    //check authentication…
    $this->getAuthService()->getAdapter()
    ->setIdentity($request->getPost(‘username’))
    ->setCredential($request->getPost(‘password’)
    );

    $result = $this->getAuthService()->authenticate();

    foreach($result->getMessages() as $message)
    {
    //save message temporary into flashmessenger
    $this->flashmessenger()->addMessage($message);
    }

    if ($result->isValid()) {
    $user_session = new Container(‘user’);
    $user_session->username = ‘Andy0708’;

    //check if it has rememberMe :
    if ($request->getPost(‘rememberme’) == 1 ) {
    $this->getSessionStorage()
    ->setRememberMe(1);
    //set storage again
    $this->getAuthService()->setStorage($this->getSessionStorage());
    }
    $this->getAuthService()->setStorage($this->getSessionStorage());
    $this->getAuthService()->getStorage()->write($request->getPost(‘username’));

    $redirect = ‘success’;

    }
    /* hoo */
    // $this->getAuthService()->getAdapter()
    // ->setIdentity($request->getPost(‘username’))
    // ->setCredential($request->getPost(‘password’));
    // $result = $this->getAuthService()->authenticate();
    // $result = $this->getAuthService()->getAdapter()->getResultRowObject();
    $usersrow = $this->get(Username($result->username));
    $this->getAuthService()->getStorage()->write(array(
    ‘username’ => $result->username,
    //other session key => value here.
    ));
    if ($this->getServiceLocator()->get(‘AuthService’)->hasIdentity()) {
    $users = $this->getServiceLocator()->get(‘Access\Model\AuthStorage’)->read();
    echo $users[‘username’]; print_r($users);}
    }
    }

    return $this->redirect()->toRoute($redirect);
    }

  117. Bharath said, on August 30, 2013 at 1:09 pm

    This is My Error :

    Entity of type Access\Entity\Level is missing an assigned ID for field ‘id’. The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called. If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.

    Then Code for this error is from Access/Entity/Level:

    id = $id;

    return $this;
    }

    /**
    * Get id
    *
    * @return string
    */

    public function getId()
    {
    return $this->id;
    }

    /**
    * Set ldesc
    *
    * @param string $ldesc
    * @return Level
    */
    public function setDescription($ldesc)
    {
    $this->ldesc = $ldesc;

    return $this;
    }

    /**
    * Get ldesc
    *
    * @param string
    */
    public function getDescription()
    {
    return $this->ldesc;
    }

    /**
    * Set enable
    *
    * @param string $enable
    * @return Level
    */
    public function setEnable($enable)
    {
    $this->enable = $enable;

    return $this;
    }
    /**
    * Get enable
    *
    * @param string
    */
    public function getEnable()
    {
    return $this->enable;
    }

    /**
    * Get entby
    *
    * @return string
    */
    public function setEnterby()
    {
    return $this->entby;
    }
    /**
    * @ORM\PrePersist
    */
    public function setEntdon()
    {
    $this->enton = new \DateTime();
    }
    /**
    * Get EntdonDate
    *
    * @return \DateTime
    */
    public function getEntdonDate()
    {
    return $this->enton;
    }
    /**
    * Get modby
    *
    * @return string
    */
    public function getModby()
    {
    return $this->modby;
    }
    /**
    * @ORM\PrePersist
    */
    public function setModon()
    {
    $this->modon = new \DateTime();
    }

    /**
    * Get Created Date
    *
    * @return \DateTime
    */
    public function getModon()
    {
    return $this->modon;
    }

    /**
    * Get authby
    *
    * @return string
    */
    public function getAuthby()
    {
    return $this->authby;
    }
    /**
    * @ORM\PrePersist
    */
    public function setAuthon()
    {
    $this->authon = new \DateTime();
    }

    /**
    * Set mapping
    *
    * @param Mapping $mapping
    * @return Level
    */
    public function setMapping(Mapping $mapping)
    {
    $this->mapping = $mapping;

    return $this;
    }

    /**
    * Get mapping
    *
    * @return Mapping
    */
    public function getMapping()
    {
    return $this->mapping;
    }

    /**
    * Exchange array – used in ZF2 form
    *
    * @param array $data An array of data
    */
    public function exchangeArray($data)
    {
    $this->id = (isset($data[‘id’]))? $data[‘id’] : null;
    $this->ldesc = (isset($data[‘ldesc’]))? $data[‘ldesc’] : null;
    $this->enable = (isset($data[‘enable’]))? $data[‘enable’] : null;
    $this->entity = (isset($data[‘entity’]))? $data[‘entity’] : null;
    $this->entby = (isset($data[‘entby’]))? $data[‘entby’] : null;
    $this->enton = (isset($data[‘enton’]))? $data[‘enton’] : null;
    $this->modby = (isset($data[‘modby’]))? $data[‘modby’] : null;
    $this->modon = (isset($data[‘modon’]))? $data[‘modon’] : null;
    $this->authby = (isset($data[‘authby’]))? $data[‘authby’] : null;
    $this->authon = (isset($data[‘authon’]))? $data[‘authon’] : null;
    $this->mapping = (isset($data[‘mapping’]))? $data[‘mapping’] : null;
    //$this->createdOn = (isset($data[‘createdOn’]))? $data[‘createdOn’] : null;
    }

    /**
    * Get an array copy of object
    *
    * @return array
    */
    public function getArrayCopy()
    {
    return get_object_vars($this);
    }

    /**
    * Set input method
    *
    * @param InputFilterInterface $inputFilter
    */
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
    throw new \Exception(“Not used”);
    }

    /**
    * Get input filter
    *
    * @return InputFilterInterface
    */
    public function getInputFilter()
    {
    if (!$this->inputFilter) {
    $inputFilter = new InputFilter();
    $factory = new InputFactory();

    $inputFilter->add($factory->createInput(array(
    ‘name’ => ‘id’,
    ‘required’ => true,
    ‘filters’ => array(
    array(‘name’ => ‘StripTags’),
    array(‘name’ => ‘StringTrim’),
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘StringLength’,
    ‘options’ => array(
    ‘encoding’ => ‘UTF-8’,
    ‘min’ => 1,
    ‘max’ => 255,
    ),
    ),
    ),

    )));

    $inputFilter->add($factory->createInput(array(
    ‘name’ => ‘ldesc’,
    ‘required’ => true,
    ‘filters’ => array(
    array(‘name’ => ‘StripTags’),
    array(‘name’ => ‘StringTrim’),
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘StringLength’,
    ‘options’ => array(
    ‘encoding’ => ‘UTF-8’,
    ‘min’ => 1,
    ‘max’ => 255,
    ),
    ),
    ),
    )));

    $inputFilter->add($factory->createInput(array(
    ‘name’ => ‘enable’,
    ‘required’ => true,
    ‘filters’ => array(
    array(‘name’ => ‘StringTrim’),
    ),
    ‘validators’ => array(
    array(
    ‘name’ => ‘StringLength’,
    ‘options’ => array(
    ‘encoding’ => ‘UTF-8’,
    ‘min’ => 1,
    ),
    ),
    ),
    )));

    $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
    }
    }

  118. bhuvanesh said, on August 30, 2013 at 1:18 pm

    // after I put this comment,
    print_r($this->getAuthService()->getAdapter()->getResultRowObject());

    it displaying this line
    stdClass Object ( [id] => 2 [username] => bhuvi [password] => bhuvi )

    within in that I need to call username alone…

  119. bhuvanesh said, on August 30, 2013 at 2:13 pm

    public function getSessionStorage()
    {
    //print_r($this->getAuthService()->getAdapter()->getResultRowObject());

    $result = $this->getAuthService()->getAdapter()->getResultRowObject();

    echo $result->username;

    $manager = new SessionManager();
    $manager->setStorage(new SessionArrayStorage());
    if (! $this->storage) {
    $this->storage = $this->getServiceLocator()
    ->get(‘Access\Model\MyAuthStorage’);
    }

    return $this->storage;
    }

    after I putting this code, I m getting username alone

    that username I need to call in success page….

  120. bhuvanesh said, on August 30, 2013 at 6:49 pm

    In controller:

    public function getSessionStorage()
    {
    //print_r($this->getAuthService()->getAdapter()->getResultRowObject());

    $result = $this->getAuthService()->getAdapter()->getResultRowObject();

    echo $result->username;

    //print_r(‘username’);
    $manager = new SessionManager();
    $manager->setStorage(new SessionArrayStorage());
    if (! $this->storage) {
    $this->storage = $this->getServiceLocator()
    ->get(‘Access\Model\MyAuthStorage’);
    }

    return $this->storage;
    }

    username must be print near to success page in logout

    how I will pass this variable to boostrap and loadconfig….

  121. bhuvanesh said, on August 30, 2013 at 8:44 pm

    controller
    Auth controller:

    authservice) {
    $this->authservice = $this->getServiceLocator()
    ->get(‘AuthService’);
    }

    return $this->authservice;
    }

    public function getSessionStorage()
    {
    //print_r($this->getAuthService()->getAdapter()->getResultRowObject());

    $result = $this->getAuthService()->getAdapter()->getResultRowObject();

    echo $result->username;

    //print_r(‘username’);
    $manager = new SessionManager();
    $manager->setStorage(new SessionArrayStorage());
    if (! $this->storage) {
    $this->storage = $this->getServiceLocator()
    ->get(‘Access\Model\MyAuthStorage’);
    }

    return $this->storage;
    }
    public function ControllerAction(){
    if ($this->getServiceLocator()->get(‘AuthService’)->hasIdentity())
    {
    $users = $this->getServiceLocator()->get(‘AuthService’)->getStorage()->read();
    echo $users[‘username’];

    }
    }
    public function getForm()
    {
    $em = $this->getEntityManager();
    if (isset($_SESSION[‘username’]) && $_SESSION[‘username’] instanceof User) {
    $form= $_SESSION[‘username’];
    $username = $em->merge($username);
    }
    if (! $this->form) {
    $user = new User();
    $builder = new AnnotationBuilder();
    $this->form = $builder->createForm($user);

    }

    return $this->form;
    }

    public function loginAction()
    {
    $session = new Container();
    //$user = new SessionManager();
    //Container::setDefaultManager($user);

    //if already login, redirect to success page
    if ($this->getAuthService()->hasIdentity()){
    return $this->redirect()->toRoute(‘success’);
    }

    $form = $this->getForm();

    return array(
    ‘form’ => $form,
    ‘messages’ => $this->flashmessenger()->getMessages()
    );
    }

    public function authenticateAction()
    {
    $em = $this->getEntityManager();
    $form = $this->getForm();
    /*
    * $user_session = new Container(‘user’);
    * $username = $user_session->username;
    * $username = $_SESSION[‘user’][‘username’];
    */

    print_r($this->getAuthService()->getAdapter()->getResultRowObject());
    $redirect = ‘login’;

    $request = $this->getRequest();
    if ($request->isPost()){
    $form->setData($request->getPost());
    if ($form->isValid()){
    $em = $this->getEntityManager();
    // $this->escapeHtml($username);
    //check authentication…
    $this->getAuthService()->getAdapter()
    ->setIdentity($request->getPost(‘username’))
    ->setCredential($request->getPost(‘password’)
    );

    $result = $this->getAuthService()->authenticate();
    // $result = $this->getAuthService()->getAdapter()->getResultRowObject();

    foreach($result->getMessages() as $message)
    {
    //save message temporary into flashmessenger
    $this->flashmessenger()->addMessage($message);
    }

    if ($result->isValid()) {
    $user_session = new Container(‘user’);
    $user_session->username = ‘Andy0708’;

    //check if it has rememberMe :
    if ($request->getPost(‘rememberme’) == 1 ) {
    $this->getSessionStorage()
    ->setRememberMe(1);
    //set storage again
    $this->getAuthService()->setStorage($this->getSessionStorage());
    }
    $this->getAuthService()->setStorage($this->getSessionStorage());
    $this->getAuthService()->getStorage()->write($request->getPost(‘username’));

    $redirect = ‘success’;
    //$em->getViewModel()->setVariable(‘modulenamespace’, $moduleNamespace);
    }
    /* hoo */
    // $this->getAuthService()->getAdapter()
    // ->setIdentity($request->getPost(‘username’))
    // ->setCredential($request->getPost(‘password’));
    $result = $this->getAuthService()->authenticate();
    // $result = $this->getAuthService()->getAdapter()->getResultRowObject();
    // $usersrow = $this->get(User($result->username));

    if ($this->getServiceLocator()->get(‘AuthService’)->hasIdentity())
    {
    $users = $this->getServiceLocator()->get(‘AuthService’)->getStorage()->read();
    echo $users[‘username’];

    }
    }
    }

    return $this->redirect()->toRoute($redirect);
    }

    public function logoutAction()
    {
    /*
    * $user_session = new Container(‘user’);
    * $username = $user_session->username;
    * $username = $_SESSION[‘user’][‘username’];
    */

    // $username now contains ‘Andy0708’

    if ($this->getAuthService()->hasIdentity()) {
    $this->getSessionStorage()->forgetMe();

    $this->getAuthService()->clearIdentity();
    $this->flashmessenger()->addMessage(“You’ve been logged out”);
    }

    return $this->redirect()->toRoute(‘login’);
    }
    }

    Module.php

    getEventManager()->getSharedManager();
    $sharedEvents->attach(‘Zend\Mvc\Controller\AbstractActionController’, ‘dispatch’, function($e) {
    $config = $e->getApplication()->getServiceManager()->get(‘Config’);

    echo ‘

    ';
    	   print_r($config);
    	   echo '

    ‘;
    });
    }
    public function getAutoloaderConfig()
    {
    return array(
    ‘Zend\Loader\ClassMapAutoloader’ => array(
    __DIR__ . ‘/autoload_classmap.php’,
    ),
    ‘Zend\Loader\StandardAutoloader’ => array(
    ‘namespaces’ => array(
    __NAMESPACE__ => __DIR__ . ‘/src/’ . __NAMESPACE__,
    ),
    ),
    );
    }

    public function getConfig()
    {
    return include __DIR__ . ‘/config/module.config.php’;
    }

    // public function onBootstrap(MvcEvent $evm)
    // {
    public function onBootstrap(MvcEvent $e)
    {
    $application = $e->getApplication();
    $sm = $application->getServiceManager();
    if (! $sm->get(‘AuthService’)->hasIdentity()) {
    $users = $sm->get(‘Access\Model\MyAuthStorage’)->read();
    print_r($users);
    echo $users[‘username’];
    }
    }
    /* $application = $e->getApplication();
    $sm = $application->getServiceManager();
    if (! $sm->get(‘AuthService’)->hasIdentity())
    {
    $users = $sm->get(‘Access\Model\MyAuthStorage’)->read();
    echo $users[‘username’];
    }
    */

    /* $config = $evm->getApplication()
    ->getServiceManager()
    ->get(‘Configuration’);

    $sessionConfig = new SessionConfig();
    $sessionConfig->setOptions($config[‘session’]);
    $sessionManager = new SessionManager($sessionConfig);
    $sessionManager->start();

    /* Optional: If you later want to use namespaces, you can already store the
    * Manager in the shared (static) Container (=namespace) field
    */
    /*Container::setDefaultManager($sessionManager);
    }
    */
    public function loadConfiguration(MvcEvent $e)
    {
    $controller = $e->getTarget();
    $controllerClass = get_class($controller);
    $users = substr($controllerClass, 0, strpos($controllerClass, ‘\\’));
    //set ‘variable’ into layout…

    $controller->layout()->users = $users;
    print_r($users);
    }
    public function getServiceConfig()
    {
    return array(
    ‘factories’=>array(
    // ‘Zend\Db\Adapter\Adapter’
    // => ‘Zend\Db\Adapter\AdapterServiceFactory’,

    ‘Access\Model\MyAuthStorage’ => function($sm)

    {
    return new \Access\Model\MyAuthStorage(‘smb’);
    },
    ‘AuthService’ => function($sm)
    {
    //My assumption, you’ve alredy set dbAdapter
    // //and has users table with columns : username and password
    //that password hashed with md5
    $dbAdapter = $sm->get(‘Zend\Db\Adapter\Adapter’);
    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter,
    ‘users’,’username’,’password’);
    $authService = new AuthenticationService();
    $authService->setAdapter($dbTableAuthAdapter);
    $authService->setStorage($sm->get(‘Access\Model\MyAuthStorage’));
    return $authService;
    },
    ),
    );

    }

    }

    today I tried lot….but I cant

    username must print to all other module..
    my task like near to logout I need to put username

  122. bhuvanesh said, on August 30, 2013 at 10:03 pm

    finally I got the output…..thanks for u…

  123. bhuvanesh said, on August 31, 2013 at 1:37 pm

    Hello sam,
    I want to redirect to separate pages for ADMIN and USERLOGIN…

    right now I m proceeding with ur source code…

    give some tips how to do…..

    • samsonasik said, on August 31, 2013 at 4:13 pm

      get the role of logged user, and add conditional for it. effort please 🙂

  124. Bharath said, on August 31, 2013 at 5:55 pm

    generate pdf document i’ll use Zendpdf to produce error and how to add a mapper to access the ZendPdf/PdfDocument in library

    • bhuvanesh said, on September 2, 2013 at 9:55 pm

      Put The correct name in your controller.. after that its works correctly..:)

  125. Bharath said, on September 2, 2013 at 10:30 pm

    module.php
    public function loadConfiguration(MvcEvent $e)
    {

    $application = $e->getApplication();
    $sm = $application->getServiceManager();

    if ($sm->get(‘AuthService’)->hasIdentity()) {
    $users = $sm->get(‘Access\Model\MyAuthStorage’)->read();
    echo $users;
    }
    }

    this module print my session variable($users).I want to access this variable to other form

  126. Bharath said, on September 3, 2013 at 1:13 pm

    after I singed my login page i gave link to both form grademaster and levelmaster….in my login table I created one column `role` if user is `admin` I want to display add,edit,delete but if user is `staff` I want to display `add` alone hiding(edit and delete)…if user is `guest` hiding all option(add,delete,modify);

  127. vasanthi said, on September 6, 2013 at 8:39 pm

    how to create filter sir pls give me sample code for filter the white space. explain it I am using doctrine2 so I am not clear that filtering concepts help me

  128. bhuvanesh said, on September 11, 2013 at 9:14 pm

    $this->add(array(
    ‘name’ => ‘category’,
    ‘type’ => ‘Select’,

    ‘options’ => array(
    ‘label’ => ‘Category’,
    ’empty_option’=>’bhuvi’,
    ‘value_options’ => $this->getOptionsForSelect(),

    ),

    public function getOptionsForSelect()
    {
    $dbAdapter = $this->adapter;
    $sql = ‘SELECT id,name FROM categories’;
    $statement = $dbAdapter->query($sql);
    $result = $statement->execute();

    $selectData = array();

    foreach ($result as $res) {
    $selectData[$res[‘id’]] = $res[‘name’];
    echo $res[‘name’];
    echo $res[‘id’];
    $b=$res[‘name’];
    echo $b;
    }

    return $selectData;
    }
    my table fields:
    title,
    contact,
    category,
    created date

    In select option the sublist r displaying but its not storing to database… any ideas…..

  129. bhuvanesh said, on September 16, 2013 at 6:32 pm

    In zf2 form

    datepicker is not working in ie and mozila….

    tell me any other way how to do nu,

  130. bhuvanesh said, on September 18, 2013 at 4:48 pm

    I need calendar in my date of birth and date of joining…

    zend/form/element/date working in chrome alone….

  131. Max Schindler said, on September 18, 2013 at 7:13 pm

    I read this tutorial and this too: https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/

    The simple Login with remember Function works great. Nice work.
    Now i want to combine both modules. It seems, as if after a successful login, no role is set.

    How can i set the role after a valid credential check?

    In my version i get redirected to the “Login Success” Screen.

    Thanks in advance,
    Max

  132. Kamal said, on September 19, 2013 at 6:31 pm

    using xampp–>>htdocs–>zf2-tutorial->module->>SanAuth:Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in C:\xampp\htdocs\zf2-tutorial\vendor\ZF2\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42 : do I have to copy paste the common–>>composer.json to zf2-tutorial–>>composer.json , If yes i did this also but again the same problem

    I just downloaded the doctrine\common and paste the common to the vendor folder and copy & paste the composer.json to from common to zf2-tutorial : please guide me to get out of this error. I also want to check the authentication without using doctrine how to do it using AuthenticationService any example.

  133. bhuvanesh said, on September 21, 2013 at 12:49 pm

    I HAVE CODE THIS LIKE IN MY INDEX ACTION(FOR FILTER):
    $q = $em->createQuery(“select B.PGM_CODE,B.PGM_NAME from Access\Entity\Program B where B.PGM_NAME LIKE ‘%PGM_NAME%'”);

    EXAMPLE:
    SELECT * FROM program
    WHERE PGM_NAME LIKE ‘%an%’;

    ITS NOT WORK,IF U HAVE ANY IDEA,TELL ME…I AM ALSO PUTTING EFFORT

    • samsonasik said, on September 21, 2013 at 2:00 pm

      please stop keep asking OOT comment on non-correlate post. or I will mark you as spam.

  134. Andrei said, on October 9, 2013 at 3:31 pm

    Hey, trying to use your module, but get this error :
    “A value for the identity was not provided prior to authentication with DbTable.”

    • Andrei said, on October 9, 2013 at 3:46 pm

      Already fix by myself. Misstype one letter :). Thx for module.

  135. priyank said, on October 10, 2013 at 7:32 pm

    hey…. bro 😦

    i dont know understand this code easily

    which is the model,controller and form

    so please help me

  136. […] wollte nach diesem Tutorial ein einfaches Login erstellen, und da warf Zend Framework 2 mir diese 'hilfreiche' […]

  137. Harish Rawat said, on October 22, 2013 at 4:05 pm

    Hi,

    I am trying the SanAuth module for login
    http://localhost/projects/zend2/public/san-auth/login
    Its showing 404 error:
    A 404 error occurred
    Page not found.

    The requested URL could not be matched by routing.
    No Exception available

    Regards
    Harish Rawat
    http://www.listop10.com

    • samsonasik said, on October 23, 2013 at 3:48 am

      check the route 🙂

      • Simon said, on December 1, 2013 at 1:25 am

        what is wrong in this route?? I am beginner sorry but i am trying to open a view with the login form but still i am gettin a 404

  138. Kamal said, on October 23, 2013 at 2:25 pm

    Hi Samsonasik,

    Can you please tell me how I can enable authentication just for a particular controller and action. What would be the most efficient way to do it.

    Thanks alot

    • samsonasik said, on October 24, 2013 at 7:11 am

      you can do this :

      
      namespace SanAuth;
      
      use Zend\Mvc\MvcEvent;
      
      class Module
      {
          public function onBootstrap(MvcEvent $e)
          {
              $em = $e->getApplication()->getEventManager();
              $em->attach('route', array($this, 'checkAuthenticated'));
          }
      
          public function isOpenRequest(MvcEvent $e)
          {
              if ($e->getRouteMatch()->getParam('controller') == 'SanAuthWithDbSaveHandler\Controller\AuthController') {
                  return true;
              }
      
              return false;
          }
      
          public function checkAuthenticated(MvcEvent $e)
          {
              if (!$this->isOpenRequest($e)) {
                  $sm = $e->getApplication()->getServiceManager();
                  if (! $sm->get('AuthService')->hasIdentity()) {
                      $e->getRouteMatch()
                          ->setParam('controller', 'SanAuth\Controller\Auth')
                          ->setParam('action', 'login');
                  }
              }
          }
      }
      
      

      you can check with list of controller(s)/action(s) when needed.

      • Kamal said, on October 25, 2013 at 7:15 am

        Thank you so much for your prompt reply. That would help me a lot. Much appreciated.

      • yahya said, on November 2, 2013 at 7:20 pm

        Dear Sam
        what is “‘SanAuthWithDbSaveHandler\Controller\AuthController'”?

  139. sanjay said, on November 8, 2013 at 1:15 pm

    Hey sam,
    how to override or redirect the 500 error in zend 2..? (Not using htaccess for redirection)..

      • sanjay said, on November 12, 2013 at 4:28 pm

        ‘router’ => array(
        ‘routes’ => array(
        ‘admin’ => array(
        ‘child_routes’ => array(
        ‘xyz’ => array(
        ‘type’ => ‘segment’,
        ‘options’ => array(
        ‘route’ => ‘/xyz[/][:action][/:id][/:xyz]’,
        ‘constraints’ => array(
        ‘action’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
        ‘xyz’ => ‘[a-zA-Z][a-zA-Z0-9_-]*’,
        ),
        ‘defaults’ => array(
        ‘controller’ => ‘xyz\Controller\xyz’,
        ‘action’ => ‘index’,
        ),
        ),
        ),
        ),
        ),
        ),
        ),

        When i use child routes it throw error to me like Uncaught exception ‘Zend\Mvc\Router\Exception\InvalidArgumentException’ with message ‘Missing “type” option, hence i gave type.. it works perfect if i use simple route with out child routing…?

        so can i know whats the issue? Is there any changed for child Routes..?

  140. Rini (@rinirinku) said, on November 12, 2013 at 6:27 pm

    Great tutorial !
    i have a doubt :
    I want to replace the default dbadapter and create a new using soap request instead of a db. one as per http://it-cook-de.blogspot.in/2013/07/zend-framework-2-custom-authentication-with-soap-webservice-part-1.html

    but it is throwing exception as “Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for AuthService”

  141. Bhuvanesh said, on November 12, 2013 at 9:46 pm

    $this->USER_PASSWORD = (isset($data[‘USER_PASSWORD’]))? $bcrypt->create($data[‘USER_PASSWORD’]):

    when I give 112 user_password it stores like this $2y$14$yPRGu.d4XJq4P38tcAXoSOMVwQ94WA1nXSZ4/BKVG7HDQ85ODV4ae in my database,

    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, ‘user’,’USER_ID’,’USER_PASSWORD’, ‘MD5(?)’);

    but it’s not login,,

  142. Bhuvanesh said, on November 13, 2013 at 4:22 pm

    public function loginAction()
    {
    $request = $this->getRequest();
    $data = $request->getPost();

    $dbAdapter = $this->getServiceLocator()->get(‘Zend\Db\Adapter\Adapter’);

    $authAdapter = new AuthAdapter($dbAdapter);

    $authAdapter
    ->setTableName(‘user’)
    ->setIdentityColumn(‘USER_ID’)
    ->setCredentialColumn(‘USER_PASSWORD’);

    $authAdapter
    ->setIdentity($data[‘USER_ID’])
    ->setCredential($data[‘USER_PASSWORD’]);

    // attempt authentication
    $result = $authAdapter->authenticate();

    if (!$result->isValid()) {
    // Authentication failed
    } else {
    $auth = new AuthenticationService();
    $storage = $auth->getStorage();

    $storage->write($authAdapter->getResultRowObject(
    ‘username’,
    ‘password’
    ));
    }
    //if already login, redirect to success page
    if ($this->getAuthService()->hasIdentity()){
    return $this->redirect()->toRoute(‘success’);
    }
    //$dbAdapter = $this->getServiceLocator()->get(‘Zend\Db\Adapter\Adapter’);
    $form = $this->getForm();

    return array(
    ‘form’ => $form,

    ‘flashMessages’ => $this->flashMessenger()->getMessages(),

    );
    }

    public function authenticateAction()
    {
    //$dbAdapter = $this->getServiceLocator()->get(‘Zend\Db\Adapter\Adapter’);
    $form = $this->getForm();

    $redirect = ‘login’;

    // $request = $this->getRequest();
    if ($request->isPost()){
    $form->setData($request->getPost());
    if ($form->isValid()){
    $this->flashmessenger()->addMessage(“Username or Password Not Valid!”);
    //check authentication…
    $this->getAuthService()->getAdapter()
    ->setIdentity($request->getPost(‘username’))
    ->setCredential($request->getPost(‘password’));

    $result = $this->getAuthService()->authenticate();
    // foreach($result->getMessages() as $message)
    // {
    // //save message temporary into flashmessenger
    // $this->flashmessenger()->addMessage($message);
    // }

    if ($result->isValid()) {
    $redirect = ‘success’;

    ERROR:A value for the identity was not provided prior to authentication with DbTable.
    USER TABLE:
    USER_ID
    USER_PASSWORD
    but in form
    username
    password

    • Julián Gorge said, on October 9, 2014 at 5:53 am

      Please, what did you add on “if(!$result->isValid()) // Authentication failed”?

  143. Sanju said, on November 14, 2013 at 12:12 am

    Hi Sam, How can I add additional conditional statements or stat check along with authentication process.
    For example, if we allow users to login whoo provide with correct username and password plus:
    1. users.status > 1
    2. users.status = 0
    3. users.status NOT IN (7,8,9)

    Any idea? Thanks in advance.

    • samsonasik said, on November 14, 2013 at 12:23 am

      the easiest way is add more conditional after it authenticated.

      $datalogin = $this->getAuthService()->getAdapter->getResultRowObject();
      if ($datalogin->status != 1) {
      $this->getSessionStorage()->clear();
      //then do what you want here... 
      
      }
      
      
      • Sanju said, on November 14, 2013 at 7:00 pm

        Thanks for reply! Isn’t there any way in authentication service itself? If not, how can we manipulate “$result->isValid()” to set false ($result = $this->getAuthService()->authenticate()) or set our custom messages if want to do at “//then do what you want here… ” location (as mentioned above) ?

      • samsonasik said, on November 14, 2013 at 7:04 pm

        create your custom adapter like this http://ikorolchuk.blogspot.com/2013/07/zend-framework-2-bcrypt-adapter-for.html

      • Sanju said, on November 14, 2013 at 7:36 pm

        Thanks again Sam! Smells like a hell lot of work need to be done on road ahead 😀

  144. Chirag said, on November 15, 2013 at 6:44 pm

    Thanks Amazing tutorial

  145. Vivek Soni said, on November 18, 2013 at 2:33 am

    Zend\ServiceManager\Exception\ServiceNotFoundException
    File:
    C:\xampp\htdocs\college\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:518
    Message:
    Zend\Mvc\Controller\PluginManager::get was unable to fetch or create an instance for getAuthService

    i am geting this error..

    //My assumption, you’ve alredy set dbAdapter

    how to set db Adapter?

  146. Yoppy Yunhasanwa said, on November 24, 2013 at 12:03 pm

    Mas, terimakasih buat tutorialnya. Artikel mas bagus sekali. Niat banget.
    Omong-omong baris ini:

    return new \SanAuth\Model\MyAuthStorage(‘zf_tutorial’);

    ‘zf_tutorial’ itu apa mas? Itu sembarang string atau apa?

    • samsonasik said, on November 24, 2013 at 2:37 pm

      itu session namespace, iya boleh 😀

      • Yoppy Yunhasanwa said, on December 3, 2013 at 10:38 pm

        Oo iya mas, barusan cek pakai print_r ternyata nama jadi nama index di $_SESSION. Terima kasih mas. Sukses selalu buat mas.

      • samsonasik said, on December 4, 2013 at 5:20 pm

        sip, Aamiin

  147. Ahmed Sliman said, on November 24, 2013 at 5:11 pm

    How can i call the auth function in other modules

    $this->getAuthService()->hasIdentity()

  148. Cao Trần Thế Vinh said, on December 3, 2013 at 3:51 pm

    Hi mister, how can I check if user was logged-in in view layout.phtml, just like show link logout if logged-in and show the login form if not.

    • samsonasik said, on December 3, 2013 at 6:06 pm

      you can create aliases of ‘AuthService’.

      'service_manager' => array(
             //other service here
      
              'aliases' => array(
                  'Zend\Authentication\AuthenticationService' => 'AuthService'  
              ),
      ),
      

      and check by identity view helper

      
      <?php if ($this->identity()) { ?>
      
          <a href="<?php echo $this->url('auth', array('action' => 'logout')); ?>">Logout</a>
      
          <?php } ?>
      
      
      • Cao Trần Thế Vinh said, on December 5, 2013 at 12:37 am

        Thank you very much.

        I have a problem with inputFilter, I set the username input required => true, when the username is empty, the form now is invalid and it redirect login view again but there’re no error message showing like “Value is required and can’t be empty”.
        So what is the reason? and how can I fix that?

  149. vung ngo tan said, on December 8, 2013 at 11:27 am

    Thanks you very much!
    Have a nice weekend!

  150. nihilis said, on December 10, 2013 at 6:57 pm

    Hi, and thanks for the guide. Implemented it, (w/o doctrine) and it all works swell. My app has multiple modules and I need the authentication to be called/checked at the beginning. I added to the Application\Module\onBootstrap a few lines and I can get the AuthService and check if the user hasIdentity or not. But once I’ve done this I can’t redirect to anyhing (as Module does not implement the Mvc Controller)..
    Thanks in advance for any help!

    Note: I’m using ver 2.2 of the fw.

  151. […] Deutsch: Ich möchte vor manchen Modulen ein Login einbauen. Das Login-Modul habe ich von hier: Zend Framework 2 : Create Simple Login Authentication using AuthenticationService with rememberMe | … Wenn ich das richtig sehe brauche ich nur diese Zeile Code: PHP-Code: […]

  152. Mohamed KHELIFI said, on December 21, 2013 at 10:15 pm

    Hi, thank you for youre tutorial, i followed your instructions, but i have this fatal error:

    Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in C:\wamp\www\zf2-tutorial3\vendor\zendframework\zendframework\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42

    any idéa???

  153. Mohamed KHELIFI said, on December 22, 2013 at 11:36 pm

    Hi, thank you for your response.
    Now i want to know: after authentification how to get user informations (ex: username)??
    thank you …

  154. Imrul said, on January 11, 2014 at 11:01 pm

    hi, it’s nice…

  155. nihilis said, on January 20, 2014 at 5:34 am

    Maybe a silly question, but what is the best way to define Application wide constants/variables in ZF2?
    Thanks!

  156. tejas said, on January 31, 2014 at 1:53 pm

    i got only 4 text box after running this code

    • samsonasik said, on January 31, 2014 at 3:21 pm

      I guess you’re using windows. if your php on windows can’t work with annotation, I suggest to built the form using extends Zend\Form normally

  157. tejas said, on January 31, 2014 at 7:43 pm

    thanks,

    i set logout link at menubar,, but i want to set it enable when we are not logged in, how can i?

  158. tej said, on February 14, 2014 at 5:30 pm

    I done this above example and it work nice but after successful logout, the form redirect to the Login page but when i go beck from the form ti will go back to the success index page.
    but i want that if we click on go back after logout it will redirect to the login page only.

  159. tej said, on February 15, 2014 at 12:44 pm

    Hii
    i have a 2 modules
    Module
    +_Application
    +_SanAuth
    +_Student

    i want to use constructure in Module like this.

    <?php

    // StudentController.php in module/Student/src/Student/Controller folder

    namespace Student\Controller;

    use Zend\Mvc\Controller\AbstractActionController;
    use Zend\View\Model\ViewModel;
    use SanAuth\Controller\AuthController;
    use Student\Model\Student; // <– Add this import
    use Student\Form\StudentForm; // $this->getStudentTable()->fetchAll(),
    ));
    }

    public function addAction()
    {
    $form = new StudentForm();
    $form->get(‘submit’)->setValue(‘Add’);

    $request = $this->getRequest();
    if ($request->isPost()) {
    $student = new Student();
    $form->setInputFilter($student->getInputFilter());
    $form->setData($request->getPost());

    if ($form->isValid()) {
    $student->exchangeArray($form->getData());
    $this->getStudentTable()->saveStudent($student);

    // Redirect to list of students
    return $this->redirect()->toRoute(‘student’);
    }
    }
    return array(‘form’ => $form);

    }

    public function editAction()
    {
    $id = (int) $this->params()->fromRoute(‘id’, 0);
    if (!$id)
    {
    return $this->redirect()->toRoute(‘student’, array(
    ‘action’ => ‘add’
    ));
    }

    // Get the Student with the specified id. An exception is thrown
    // if it cannot be found, in which case go to the index page.
    try
    {
    $student = $this->getStudentTable()->getStudent($id);
    }
    catch (\Exception $ex)
    {
    return $this->redirect()->toRoute(‘student’, array(
    ‘action’ => ‘index’
    ));
    }

    $form = new StudentForm();
    $form->bind($student);
    $form->get(‘submit’)->setAttribute(‘value’, ‘Edit’);

    $request = $this->getRequest();
    if ($request->isPost())
    {
    $form->setInputFilter($student->getInputFilter());
    $form->setData($request->getPost());

    if ($form->isValid())
    {
    $this->getStudentTable()->saveStudent($student);

    // Redirect to list of students
    return $this->redirect()->toRoute(‘student’);
    }
    }

    return array(
    ‘id’ => $id,
    ‘form’ => $form,
    );
    }

    public function deleteAction()
    {
    $id = (int) $this->params()->fromRoute(‘id’, 0);
    if (!$id)
    {
    return $this->redirect()->toRoute(‘student’);
    }

    $request = $this->getRequest();
    if ($request->isPost())
    {
    $del = $request->getPost(‘del’, ‘No’);

    if ($del == ‘Yes’) {
    $id = (int) $request->getPost(‘id’);
    $this->getStudentTable()->deleteStudent($id);
    }

    // Redirect to list of students
    return $this->redirect()->toRoute(‘student’);
    }

    return array(
    ‘id’ => $id,
    ‘student’ => $this->getStudentTable()->getStudent($id)
    );
    }

    public function getStudentTable()
    {
    if (!$this->studentTable)
    {
    $sm = $this->getServiceLocator();
    $this->studentTable = $sm->get(‘Student\Model\StudentTable’);
    }
    return $this->studentTable;
    }
    }

    ?>

    And

    getAuthService()->hasIdentity())
    {
    return $this->redirect()->toRoute(‘login’);
    }
    /* if (!$this->getAuthService()->hasIdentity()) //->getStorage()->get(username)
    {

    return $this->redirect()->toRoute(‘login’);

    }
    */
    }

    public function getAuthService()
    {
    if (! $this->authservice) {
    $this->authservice = $this->getServiceLocator()->get(‘AuthService’);
    }

    return $this->authservice;
    }

    public function getSessionStorage()
    {
    if (! $this->storage) {
    $this->storage = $this->getServiceLocator()
    ->get(‘SanAuth\Model\MyAuthStorage’);
    }

    return $this->storage;
    }

    public function getForm()
    {
    if (! $this->form) {
    $user = new User();
    $builder = new AnnotationBuilder();
    $this->form = $builder->createForm($user);
    }

    return $this->form;
    }

    public function loginAction()
    {
    //if already login, redirect to success page
    if ($this->getAuthService()->hasIdentity())
    {
    return $this->redirect()->toRoute(‘success’);
    }

    $form = $this->getForm();

    return array(
    ‘form’ => $form,
    ‘messages’ => $this->flashmessenger()->getMessages()
    );
    }

    public function authenticateAction()
    {
    $form = $this->getForm();
    $redirect = ‘login’;

    $request = $this->getRequest();
    if ($request->isPost())
    {
    $form->setData($request->getPost());
    if ($form->isValid())
    {
    //check authentication…
    $this->getAuthService()->getAdapter()
    ->setIdentity($request->getPost(‘username’))
    ->setCredential($request->getPost(‘password’));

    $result = $this->getAuthService()->authenticate();

    foreach($result->getMessages() as $message)
    {
    //save message temporary into flashmessenger
    $this->flashmessenger()->addMessage($message);
    }

    if ($result->isValid())
    {
    $redirect = ‘success’;
    //check if it has rememberMe :
    if ($request->getPost(‘rememberme’) == 1 )
    {
    $this->getSessionStorage()
    ->setRememberMe(1);
    //set storage again
    $this->getAuthService()->setStorage($this->getSessionStorage());
    }
    $this->getAuthService()->setStorage($this->getSessionStorage());
    $this->getAuthService()->getStorage()->write($request->getPost(‘username’));
    }

    }
    }

    return $this->redirect()->toRoute($redirect);
    }

    public function logoutAction()
    {
    if ($this->getAuthService()->hasIdentity())
    {
    $this->getSessionStorage()->forgetMe();
    $this->getAuthService()->clearIdentity();
    $this->flashmessenger()->addMessage(“You’ve been logged out”);
    }

    return $this->redirect()->toRoute(‘login’);
    }

    }

    After do this when i will run this example it will give error like :

    Fatal error: Call to a member function get() on a non-object in /var/www/team/roshan/ZendSkeletonViewDemo/module/SanAuth/src/SanAuth/Controller/AuthController.php on line 40

    my line number 40 is $this->authservice = $this->getServiceLocator()->get(‘AuthService’);

    how can i solve this

  160. tuannguyen said, on February 24, 2014 at 11:22 am

    thanks you, but you can give me full code? I can’t it.

    • samsonasik said, on February 25, 2014 at 5:00 am

      read again the post, I have linked my github repo on it.

  161. tejas said, on February 24, 2014 at 5:53 pm

    hello sir,

    i want to make a send Email Module for Zendframework 2.
    you have any created example ?

    i am waiting for your reply sir

  162. Dara Sun said, on February 26, 2014 at 2:07 pm

    hi ! Mr Samsonasik
    thank for this tutorial but i have any problem
    it error DoctrineAnnotationParser.php

  163. Trung Nguyen said, on March 2, 2014 at 9:11 pm

    Hi, Samsonasik

    If use Zend\Crypt\Password\Bcrypt to encrypt passwords, how to accurately AuthenticationService

    help me !!

  164. Валерий Узун said, on March 3, 2014 at 11:18 pm

    HI! Thank you for your tutorial! Its really good!

    I’m newbie Zend Development and in web programming at general. Whats why i have question!
    I did Zend framework 2 tutorial (album) and know want to integrate Authentication Function to Album module, but staked. I have changed SanAuth to album everywhere and added Album name spaces to AuthController.php and to SuccessController.php now i’m getting:

    Zend\View\Renderer\PhpRenderer::render: Unable to render template “album/auth/login”; resolver could not resolve to a file

    I’m lost in this forest. Can you guide me to right direction? i can’t figure it out myself. Sorry for my English, if you have seen errors!

    Thank You!

    • samsonasik said, on March 4, 2014 at 2:27 am

      then you need to have album/auth/login.phtml under view folder.

  165. gihandilanka said, on March 17, 2014 at 1:01 pm

    return new \SanAuth\Model\MyAuthStorage(‘zf_tutorial’);

    hi, what do we enter instead of ‘‘zf_tutorial’,
    because this is not clear, I think setStorage is not working, always getIdentity is empty..

    • samsonasik said, on March 19, 2014 at 7:21 am

      that’s session storage namespace, you can type other. please read the zf2 code

  166. jeffry said, on March 28, 2014 at 11:30 pm

    when I add “SanAuth” in config/application.config.php the app return a error 500. Can you help me please?

  167. Ravindra Singh said, on April 10, 2014 at 11:18 am

    Hi Samsonasik,

    Thanks for this tutorial!

    I have implemented your code in Application module as per your instructions. But when go to view page “auth/login” there i get all (4) fields as “text” field. I am new to ZF2 & do not understand how to get fields as Username (text), Password (text), Remember me (radio) and Submit (submit).

    I have a users table having columns “id”, “user_name”, “pass_word” and few extra fields.

    Can you please sort it out?

    Thanks,

    • samsonasik said, on April 10, 2014 at 6:49 pm

      did you use windows ? 😛 , I think windows env have issue with doctrine annotation. please use linux/mac instead, or if you stick with windows, you need to extends Zend\Form\Form instead.

  168. Ravindra Singh said, on April 10, 2014 at 7:16 pm

    I got it working!

    Missed to import ” use Zend\Form\Annotation;” in User.php 🙂

    Thanks for the quick response. Good Work. (y)

  169. Psychodelics said, on April 13, 2014 at 7:21 am

    Hi samsonasik, I like your tutorial but I have two questions.

    I want to add following lines to my onBootstrap to load the User-Class for the authenticated user:
    $id = $e->getApplication()->getServiceManager()->get(‘AuthService’)->getIdentity();
    $user = new User($id);

    How should I save this Instance, to use it in my whole application? Maybe I need this Instance in layout, controllers, models and views.

    And I have a second question:
    Do you have a tutorial for ACL?

    Thanks

  170. Zend framework 2 info | urlcatalog said, on April 23, 2014 at 11:11 pm

    […] Create Simple Login Authentication Database Table […]

  171. ravindra Singh said, on April 29, 2014 at 12:04 am

    Hi samsonasik,

    Thanks, Your tutorial is working fine for me.

    The only thing i am confused with, is: How could i use “remember me” functionality using cookie? Like:- if previously i have checked “checkbox” and when i come next time , enter my username then it should auto fill the password field geeting from cookie.

    Is that make any sense or i have misunderstood your concept?

  172. ravindra Singh said, on April 29, 2014 at 12:06 am

    I have one more requirement:
    Can you please suggest me any simple functionality to implement the forgot password functionality along with this module?

    Thanks, (y)

  173. tomytree22 (@tomytree22) said, on April 29, 2014 at 9:23 pm

    Thks for the article very useful.

  174. Dipanjan bagchi said, on May 1, 2014 at 3:15 pm

    Hi samsonasik,

    I got a problem while executing this application. The login page is not visible..
    Can you please help me out???
    My error is shown below when i m going to open the form..

    Fatal error: Class ‘Doctrine\Common\Annotations\AnnotationRegistry’ not found in C:\xampp\htdocs\zend_tutorial\vendor\zendframework\zendframework\library\Zend\Code\Annotation\Parser\DoctrineAnnotationParser.php on line 42

  175. Hans said, on May 9, 2014 at 4:22 am

    Hi, many thanks for your tutorials! I’m a Zend newbie and have a problem. I want to use san-auth for other modules. The User have to login to use all my modules. How can i solve this?
    I read some hints here, but i have problems to follow the answers.
    Hope you help me.
    regards
    Hans

  176. Ben said, on May 14, 2014 at 7:34 pm

    As a newcomer to Macs, I thought the red button quits the browser. It just closes the window whilst the browser is still open in memory. You have to go to File > Quit to do this. This ends the browser session and kills the browser process. When the browser is restarted it will show the login page if the ‘remember me’ has been unchecked after logging in previously.

  177. Ivan said, on June 5, 2014 at 2:58 am

    Hi, many thanks for your tutorials! I’m sorry for my english.
    I’m using :

    ZF2 v2.3.*

    global conf:

    ‘db’ => array (
    ‘driver’ => ‘Pdo’,
    ‘dsn’ => ‘dblib:dbname=DATABASE;host=NEW_MSSQL;’,
    ‘charset’ => ‘UTF-8’,
    ‘pdotype’ => ‘dblib’ ,
    ‘platform’ => ‘SqlServer’,
    )

    and, in `authenticateAction` in `AuthController` i have error :

    The supplied parameters to DbTable failed to produce a valid sql statement, please check table and column names for validity.

    so I check and find error in generated SQL statment:

    SELECT dbo.[user].*,
    (CASE WHEN [passw] = LOWER( CONVERT(VARCHAR(32), HashBytes(‘MD5’, ‘:column1’), 2)) THEN 1 ELSE 0 END) AS [zend_auth_credential_match]
    FROM [user]
    WHERE [name] = :where1

    as You can see `:column1` and `:where1` didn’t changed, is it a bug or what ?

    Everything else in sample skeleton application working !

    • samsonasik said, on June 6, 2014 at 9:19 am

      don’t be hurry to say that’s a bug, please check the error carefully and the code carefully and you will find the solution.

      • Ivan said, on June 6, 2014 at 3:35 pm

        Thank you for your prompt response!
        However, debugging ZF came to the part where it creates a SQL query, and then came to bad SQL, and as such sent to the server for execution.
        Didn’t try with MySQL or other servers…

  178. dcparham said, on June 12, 2014 at 9:00 pm

    Thanks for this; I really need a step by step tutorial. Your title looked promising, but I must move on.

  179. Zirmo said, on June 20, 2014 at 9:55 pm

    Hi samsonasik, great work here. I just started with ZF2 and it helped me a lot. One Question if you mind: In my Database i added a field called Groups(0 for user / 1 for admin). Any good way to check it (Admin/User princip)? Best regards, keep the good work up!

    • samsonasik said, on June 21, 2014 at 4:26 am

      you can check rows after authenticate :

      print_r($this->getAuthService()->getAdapter()->getResultRowObject());
      

      and check the results.

  180. Bala said, on June 25, 2014 at 7:04 pm

    Hi

    How to store the userid in the album table can u help me.I stored the userid like the below code.

    $this->getAuthService()->getStorage()->write(array(
    ‘id’ => $result->id,
    ‘username’ => $result->user_name,
    ));
    I need to store the album details with user id how can i do this.

  181. Nam Nguyễn said, on June 26, 2014 at 8:51 am

    @Bala: do you follow this article http://framework.zend.com/manual/2.0/en/user-guide/database-and-models.html? If yes, why do you have to set id when id is increment?

  182. Ravindra said, on July 29, 2014 at 1:51 am

    Hi Samsonasik, Good Work!
    Login form is working fine on localhost and Godaddy hosted website. But i am trying to use same code for my another project, it through an error “No element by the name of [username] found in form”

    Here is link to login form: http://tritechsmartsolutions.com/sfscrm/auth/login/admin
    Is there may be any server problem or something else? I am new in ZF2 🙂

    • samsonasik said, on July 31, 2014 at 1:39 am

      Hi, it should be the field name is not registered in your form. please check case sensitive on it.

      • Ravindra said, on July 31, 2014 at 11:02 am

        Thank you for the reply.
        The form was fine on local server. Then i checked php version on that server, it was below 5.3.3 . After upgrading php version it is working fine. 🙂

      • samsonasik said, on July 31, 2014 at 2:08 pm

        great! 😉

  183. […] Create Simple Login Authentication Database Table […]

  184. guest said, on August 21, 2014 at 9:41 pm

    Hi, Samsonasik!

    How can I use this
    $this->getServiceLocator()
    ->get(‘AuthService’)->hasIdentity())
    in view/layout?

    Thanks for help!

  185. zend2 login said, on August 30, 2014 at 1:20 pm

    […] Zend Framework 2 : Create Simple Login Authentication using … […]

  186. Eike said, on October 28, 2014 at 12:10 am

    Maybe this question was asked many times before, but I’ll ask it again:

    In my AuthController I have something like this:
    $user = $em->getRepository(‘Main\Entity\User’)->findOneByName($request->getPost(‘username’));
    $this->getAuthService()->getStorage()->setUser($user);

    So I extended my Storage with the attribute user.

    In other Controllers I would like to know the user I set in AuthController

    I’m doing like this:
    $user = $this->getServiceLocator()->get(‘AuthService’)->getStorage()->getUser();

    But the user is null. What am I doing wrong?

  187. Thành Trọng Lê said, on November 11, 2014 at 10:01 pm

    please tutorial to run this project.tks!

  188. Dusyant Rana said, on November 12, 2014 at 8:38 pm

    Hi ,,,i wrote same code with all settings in config files,,but it is showing below error..

    zend\serviceManager\serviceManager::get was unable to fetch or create an instance for zend\db\Adapter\Adapter…

    please provide me solution..i m using zend 2.3 version…..have to do same task

  189. Dusyant Rana said, on November 13, 2014 at 1:50 pm

    i m working to setup Zend Authentication for user name and password as session ,in module.php i have done all settings and getting error : Application\DbTableAuthAdapter not found.

    in getServiceConfige method of module.php ..i wrote the code …which is throwing above error..

    ‘AuthService’ => function($sm)(
    $dbadapter = $sm->get(‘Zend\Db\Adapter\Adapter’);
    $dbtableauthadapter = new DbTableAuthAdapter($dbadapter,’tablename’,’username’,’password’,’MD5(?)’);
    $authservice = new AuthenticationService();
    $authservice->setAdapter($dbtableauthadapter);
    $authsevice->setStorage($sm->get(‘modulename\Model\myauthstoragefile’));
    return $authservice;
    )

    in myauthstoragefile…only one function exists containing remember me functionality

    any solution for above error…m just creating session username and password with Zend Auth library

    • samsonasik said, on November 14, 2014 at 2:48 am

      you need to add :

      use Zend\Authentication\Adapter\DbTable as DbTableAuthAdapter;
      

      don’t be hurry to learn! and do effort!

  190. Dusyant Rana said, on November 14, 2014 at 12:57 pm

    i already added this in module.php

  191. seyferx said, on December 16, 2014 at 11:28 am

    I’m trying change remember me param in auth_storage, but it doesn’t work.

  192. bharath said, on December 20, 2014 at 4:13 pm

    hi sam,
    i want to seperate users like admin user and normal user in application.
    once login any one of the user admin or user both are directly went to success page.
    there both are different module user like application and admin as Admain
    and also different table user and admin.
    how to solve this exception in zf2 using adaper……….hlp me sam…………….

  193. sunnrunner said, on January 15, 2015 at 1:10 pm

    Ok, I’ve figured out how to authenticate users but, I’m using Apigility’s built in authorization https://apigility.org/documentation/auth/advanced and I don’t know how to get through the authentication. I’m assuming I do it through onBootstrap in the module.php but, cannot figure it out.

    essentially I have something like

    public function onBootstrap(MvcEvent $event)
    {
    if (!is_null($authentication->getZendAuthenticationService()->getIdentity())) {
    // user is authenticated so maybe i can put something here to tell apigility it’s ok to proceed to executing the request?
    }
    }

    Thanks for any help

    • samsonasik said, on January 15, 2015 at 10:39 pm

      i don’t have idea with apigility right now, based on the documentation you provide, it should be comes from the ‘service’ with name : ‘authentication’. so, the $authentication should callable by :

      $event->getServiceManager->get('authentication');
      

      or

      $event->getServiceManager->get('api-identity');
      

      you may consult in apigility mailing list : https://groups.google.com/a/zend.com/forum/#!forum/apigility-users for the right approach ;).

  194. diater said, on January 21, 2015 at 12:01 pm

    whether we can changed the auth form design. if so how?

  195. Erick said, on January 21, 2015 at 7:28 pm

    Very great article Sam, Thanks.
    As you already know, I can initialised a session variable like this $sessionData = new Zend\Session\Container();
    and use it for exemple to save a user name by doing this $sessionData->name = “Sam”;

    Since “MyAuthStorage” extends Storage\Session, I want to know if I can use the variable $storage you defined in “AuthController” to dispatch the username during all the session.

    Ok. What I forgot to say I tried but it didn’t work. Now I want to know how I can adapt your code to dispatch a session variable because I don’t want to redefine a new Zend\Session\Container().

    Thanks in advance.

    • samsonasik said, on January 21, 2015 at 8:00 pm

      as default session object member name named ‘storage’, you can set other with create new methods in AuthStorage class, like this :

          public function setMember($member)
          {
              $this->member = $member;
      
              return $this;
          }
      
          public function getMember()
          {
              return $this->member;
          }
      

      and you can set other member when doing set session write :

              $auth->getStorage()->setMember('foo')
                   ->write( (object) array('bar' => 'baz') );
              var_dump(
                  $auth->getStorage()->setMember('foo')->read()
              );
      

      and if you want to call default ‘storage’ member, you can switch with setMember again :

              // Switch Default session object member name
              $auth->getStorage()->setMember('storage');
              var_dump($auth->getStorage()->read());
      
      • Erick said, on February 2, 2015 at 3:28 pm

        Thanks

  196. ccbb said, on January 21, 2015 at 8:42 pm

    Hi,
    Thanks for the good example, I use it and it works great. Now I need to extend it even more, in order to get the real username and id of an user at logon. I’d like to do this in the AuthController under loginAction but there I have no db connector. I thaught of using Zend\Db\Adapter\Adapter, in ModAuth\Module but the contructor would then need to implement TableGateway, which is not an option..

    Any ideas/tips?

    thanks!

  197. omayma hamdi said, on January 27, 2015 at 10:41 pm

    Fatal error: Uncaught exception ‘Zend\Mvc\Router\Exception\RuntimeException’ with message ‘Route with name “SanAuth” not found’ in D:\wamp\www\test\vendor\zendframework\zendframework\library\Zend\Mvc\Router\Http\TreeRouteStack.php on line 317

    • samsonasik said, on January 29, 2015 at 11:05 am

      please don’t only paste the error :P, anyway, your error already show you the reason, there is no route named SanAuth, based on this post, it should be named ‘login’.

  198. vilas zade said, on January 28, 2015 at 7:02 pm

    Hi samsonasik, in my application we are using rest based api. On client side we are using ext.js to make service request and services are implemented using zf2 with doctrine. We tried the same implementation as you suggested in your blog but are facing following issues.

    1. User is not remembered after default session time out (24 min) if browser is kept idle.
    2. User is getting logged out once it reaches the remember me time even if user is accessing the application and session is active.
    3. When I researched on internet regarding timeout issue, it says that we need to update session gc.maxlifetime to remember me sec if we don’t want to logout after session idle timeout. We don’t want to change any settings on server side.
    Could you please help us resolving above issues. Thank you in advance

    • samsonasik said, on January 29, 2015 at 11:07 am

      you probably need to force do :

      ini_set('session.gc_maxlifetime', $time);
      

      on “setRememberMe()” method.

  199. Doopin said, on February 5, 2015 at 6:11 pm

    Thanks Sam for this great tutorial.
    It was very usefull for my App. But I need more help please.
    You defined this method getServiceConfig() in Module.php.
    I am writing a custom controller plugin for authentication and I have many issues while trying to gain access to “AuthService” (defined in getServiceConfig() ) in this plugin. Please how can I achieve this?
    I need this to apply the “hasIdentity()” method in this plugin and append it to all controller of my App;
    So I can check if a user is logged before rendering a view.
    Thanks in advance

    PS: this one of your tutorial which give me that Idea -> https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/

  200. cb said, on February 8, 2015 at 5:48 pm

    Hi and thanks for the tutorial!
    Just a question: as DbTableAuthAdapter is deprecated, do you have an updated version of the login auth? Or any recommendation?

    thanks!

  201. ccbb said, on February 11, 2015 at 10:13 pm

    hi,
    how do I create an exception for a route that is will not be controlled by the auth module? Right now everything points me to the login form unless I’m logged in..

    thanks1

  202. FraGoTe said, on March 18, 2015 at 9:16 pm

    Zend\Authentication\Adapter\DbTable was marked as deprecated

    • samsonasik said, on March 19, 2015 at 5:30 am

      yes, use Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter instead

  203. Renée said, on March 23, 2015 at 2:46 pm

    Hi,
    How you use user_id on controller via Zend_Auth.
    I’m useing this code on my controller:
    $identity = Zend\Auth::getInstance()->getIdentity()->user_id;
    But there are an error:
    Fatal error: Class ‘…\Zend\Auth’ not found
    It looks like a basic error but i don’t solve it.
    Thanks you

  204. MIQUEIAS RAFAEL said, on June 3, 2015 at 9:57 am

    how do you retrieve the name of the user logged in? success?

  205. Miquéias Rafael said, on June 11, 2015 at 6:27 am

    good’m starting with Zend Framework 2, then I am creating my first project, I used the module you created as an example. I am now sure how to return the name of the logged in user. Thanks in advance!

    • Miquéias Rafael said, on June 11, 2015 at 6:30 am

      Good I used this code in view, still not returned the name of the logged in user.

      identity ()) {
           echo ‘logged in as’. $ this-> escapeHtml ($ user-> getUsername ());
      } Else {
           echo ‘Not logged in’;
      }

  206. MIQUEIAS RAFAEL said, on November 3, 2015 at 11:00 pm

    How can I do to retrieve user information logged in item (7. The success view) ?

    Already thanks!

  207. Sahoo said, on December 23, 2015 at 3:15 pm

    Hi Samsonasik,

    Thank you for such great post. I have implemented your code in my project and its working perfectly. I have one query, if we have three fields (i.e username, password and mobile number), How can I validate these three field using Zend Auth? In this post we can validate two field.

    Thank you.

  208. dnsahoo said, on December 24, 2015 at 5:41 pm

    Thank you Sam for such helpful blog.

  209. Jani said, on March 14, 2016 at 6:59 pm

    Any idea on how to extend the session on every page load or on how to get the actual expiration time of the session? I would like to have session length as 30 minutes and the program would only log out if it has been idle for that time. I would also want to be able to warn the user that if he/she is about to be logged out after 28 mins of idleness or so (that check would be handled by javasctipt)

  210. Ayaz Khan said, on June 3, 2016 at 12:09 am

    Hello Samsonasik, I am very new to ZF2, I follow your tutorial, It works and it is very helpful to me, however I got deprecation, which is:
    “Deprecated: You are retrieving the service locator from within the class SanAuth\Controller\AuthController. Please be aware that ServiceLocatorAwareInterface is deprecated and will be removed in version 3.0, along with the ServiceLocatorAwareInitializer. You will need to update your class to accept all dependencies at creation, either via constructor arguments or setters, and use a factory to perform the injections. in C:\xampp\htdocs\practice\vendor\zendframework\zend-mvc\src\Controller\AbstractController.php on line 258”

    I also search many tutorials about this issues, but I don’t got where to put such codes, So please help me , I will be very thankful to you.

    • samsonasik said, on June 3, 2016 at 10:01 am

      you should not pull servicelocator from controller, build controller using factory instead.

  211. golnaz said, on November 30, 2016 at 12:11 am

    Hi, thanks for your posts. They are very helpful.
    My question is about how to make this authentication a token based auth. (I am very new to ZF2).
    What I’m trying to do is to modify the code so that before we send the successful login data back to the client, we can make a call to another API get a token from it and then send the token with the user login data (on the header) to the client. I read your post about attaching the event “authenticate.success” to the zfcAuthEvents onBootstrap, but I think that event gets fired after a successful login. I’m looking for a spot that i could make the call to another API, get a valid token and send it to the client with the user data.

    I’ll appreciate any help,
    Thanks.

    • samsonasik said, on November 30, 2016 at 6:55 pm

      You can create authentication adapter for it. For example:

      namespace Application\Adapter;
      
      use Zend\Authentication\Adapter\AbstractAdapter;
      use Zend\Authentication\Adapter\AdapterInterface;
      use Zend\Authentication\Result;
      
      class ApiAdapter
          extends AbstractAdapter
          implements AdapterInterface
      {
          /**
           * @var array
           */
          private $data;
      
          /**
           * @param  array  $data
           */
          public function setData(array $data)
          {
              $this->data = $data;
          }
      
          /**
           * @return Result
           */
          public function authenticate()
          {
              // API CALL that RETURN TOKEN WHEN SUCCEED here  
              // with provided "data" setted in setData()
              $clientResult = APICALL($this->data);
              
              if (!$clientResult->success) {
                  return new Result(Result::FAILURE, null);
              }
      
              return new Result(RESULT::SUCCESS, $clientResult->data);
          }
      }
      

      So, you can define your `AuthenticationService` via factory:

      namespace Application\Factory;
      
      use Application\Adapter\ApiAdapter;
      use Application\Storage\AuthStorage;
      use Zend\Authentication\AuthenticationService;
      
      class AuthenticationServiceFactory
      {
          public function __invoke($container)
          {
              $adapter = new ApiAdapter();
              return new AuthenticationService(
                  null,
                  $adapter
              );
          }
      }
      

      Then, register it:

      'factories' => [
          'AuthService' => Application\Factory\AuthenticationServiceFactory::class,
      ],
      

      So, in auth controller, you can do:

      $data = [
         'username' => $post['username'],
         'password' => $post['password'],
      ];
      $this->authService->getAdapter()->setData($data);
      $result = $this->authService->authenticate();
      
      $alert = [];
      if ($result->isValid()) {
          $identity    = $result->getIdentity();
          // set session token here by the result->getIdentity() which contains api token result here     
      }
      

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: