Zend Framework 2 : Create Simple Login Authentication using AuthenticationService with rememberMe
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
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!
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
I need Your help In zf2 pls contact me on itsvishwa01@gmail.com
please by me a coffee first 🙂 https://samsonasik.wordpress.com/buy-me-a-coffee/
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.
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.
Excellent tutorial samsonasik, thanks.
I have question, Why the class user? I not understand.
Sorry, my English isn’t good.
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.
Thank you so much my friend for your tutorial that works good 🙂
[…] https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authen… […]
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
You register MyAuthStorage and AuthService into ServiceManager that can be call by ServiceLocator. With ServiceManager, you can implement Service of Control design pattern. Constructor injection + inversion of control makes it easy to determine which classes are dependent on other classes.
For detail explanation, read this : http://zendblog.shinymayhem.com/2012/09/using-servicemanager-as-inversion-of.html
I’ve updated this post to remove hard coded dependencies in the form of type-hinting, among other things. See http://zendblog.shinymayhem.com/2013/09/using-servicemanager-as-inversion-of.html
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
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 :
Nah, di controllernya :
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. 😉
btw cara ganti pesan A record with the supplied identity could not be found. lewat mana? bisa minta referensinya?
Thanks
dari
kamu bisa dapatkan
nya.
Nah, tinggal dicoba deh seperti ini :
Bisa baca ini deh : http://zf2.readthedocs.org/en/latest/modules/zend.authentication.intro.html
Hi Samsonik,
How do we show the user fullname from the database?.
TQs
read the docs : http://zf2.readthedocs.org/en/latest/modules/zend.authentication.adapter.dbtable.html
Thanx
You’re welcome 😉
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
check template_path_stack in module.config.php . in zf2 manual, album/album is because the module named Album, and controlled named Album too. check latest manual http://zf2.readthedocs.org/en/latest/index.html , if your module is camecase, for ex : SanAuth, view folder should be san-auth/controllername
Oh I see. Thanks. By the way, now that I have 2 modules – /module/Album and /module/SanAuth, is it possible to let user login first via SanAuth before accessing Album?
you’re welcome. you can read my previous post https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/
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,
check via $_SESSION global var.
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) {
}
}
}
}
i think session writing process was failed, check before redirecting after login succeded.
Hi,
where I have to start writing the session?
Thank
Pedro
for standalone usage, you can instantiate Zend\Session\Container
Thanks from London, your tutorials are unbelievable
You’re welcome
Hey man,
do you have any source code for user authentication with acl?
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
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
it’s a good idea, thanks.
Hi samsonasik,
how can i load different layout after the login success?aslo how do pass the common controller data to the layout
?
TQs
you can add eventmanager in Module.php
for common variable to layout/view, see my post : https://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
Thanks Buddy
Where is the layout() method
see this : https://github.com/zendframework/zf2/blob/master/library/Zend/Mvc/Controller/Plugin/Layout.php#L52 , layout() is by __invoke() function. read this http://www.php.net/manual/en/language.oop5.magic.php#object.invoke
could you tell me how get the user name stored in future or in other module?
$this->getServiceLocator()->get(‘AuthService’)->getStorage()->read()?
calling from controller action :
calling from Module.php
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?
don’t mix native php function with framework. define namespace to Session component if you want other needed.
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
in Yourmodule/config/module.config.php
thanks you! you are a creative admin! (y)
You’re welcome 😉
I has received “incorrect redirection” in routes, how to fix it?
thanks
Check your route setting
I so copy and paste your code, nothing more.
Please see my code https://github.com/IgorDePaula/module-teste-zend-2
I so copy and paste your code, nothing more.
Please see my code https://github.com/IgorDePaula/module-teste-zend-2
Clone from my github : https://github.com/samsonasik/SanAuth
I installed your code as module of my application and i has this exception when i tried access one of your routes
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Zend\Db\Adapter\Adapter
configure your db adapter first : http://zf2.readthedocs.org/en/latest/user-guide/database-and-models.html
No, your code has lines code commented.
I comment the code because it should be already defined in global.php. btw, You better to read the docs from the beginning : http://zf2.readthedocs.org/en/latest/ 🙂
ok, I find the error: i tried join this tutorial with other tutorial https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/ and do failure…
what error ? try to set the priority to -, or change dispatch with render.
the error is that both the tutorials are incompatibles, don’t complement.
They execute alone, but joined no.
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)
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.
please give me specific error, so i can help you 🙂
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.
You can’t redirect to route that not registered. based on my post, try to change with :
i tried this form, i tried with login, login/process, and does not excecute too.
try to redirect manually, by native php header(‘location’). i’m curious this is apache problem.
Message:
Route with name “auth” not found
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 ??
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.
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.
No, i haven’t problem with this header. I have put this codes in different modules?
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 😉
and if I put the code in a repository, can you see him and look for an error?
just try it 🙂
https://github.com/IgorDePaula/module-teste-zend-2, look, please…
1. You should place SuccessController in your src/Teste/Controller folder.
2. in this case, getSessContainer() should call servicelocator that call AuthService.
and change the code get role in doAuthorization($e) function.
Btw, try to debug by print_r and die the data you getted :).
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
Oops, use $this instead $e in getting servicelocator.
i mean :).
the following continue: Message:
Route with name “auth” not found
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);
}
}
Your route named ‘login’
route maned login do not working too.
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
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?
good idea :), thanks
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?
Have you try to set set session.cookie_lifetime = 0 in php.ini ?
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?
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”
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!
set your session.cookie_domain = “.yourdomain.com” . ZF2 use cookie for remember-ing the session. You’re welcome.
How to configure not use cookie for saving rememberme token, but use db table?
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!
maybe like this :
Thank you man! Your replies have been very helpful!
You’re welcome 😉
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;
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?
good idea, thanks.
Here is authentication example with ZF2 with doctrine but how with only ZF2 without doctrine
extends Zend\Form\Form
Where is extends Zend\Form\Form ?
I m learner of ZF2.
Thanks in advance.
read user guide : http://zf2.readthedocs.org/en/latest/
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..
read this : https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/
Thanks. My authentication process are done with doctrine. 🙂
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.
maybe something like this :
Thank you very much it is very useful to me.
You’re welcome 😉
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;
},
In your case, for DbTableAuthAdapter, don’t pass a treatment :
and pass your secured data to setCredential in authentication process:
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?
add: verify() method needs the uncrypted password as param.
Do you know if there is a method similar to authenticate but for Bcrypt class?
not yet, i will take a look at that.
Hey, Dr. Dre,
based on this article : http://www.zimuel.it/en/english-cryptography-made-easy-with-zend-framework/
You should setSalt first :
before create :
but isn’t a little limiting to always use the same salt? using just bcrypt and verify is pb the better way..
yes!, that’s better ;). I was just answering the question 😉
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.
good idea, thanks.
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
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?
you can set it in layout by injecting layout variable. It can be done via Module.php
and you can call it in the layout :
Thanks! I’ll try it out!
You’re welcome 😉
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.
if column salt is exist, it should be work. try to update you zf2 to the latest master here : https://github.com/zendframework/zf2/
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)).
i’m using git to sync local and github master branch, and just work 🙂
Do you use a latin codification in datatable fields(password and salt)? I changed it to utf8 and It worked! 😉 Hope it helps you
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
see the apache error log.
thx.I’ll try it out
You’re welcome 😉
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?.
see the latest doc here : http://zf2.readthedocs.org/en/latest/modules/zend.authentication.adapter.dbtable.html
make sure you’re using latest zf2 master from github : https://github.com/zendframework/zf2
Hi, me again, i was doint it with a postgres database, and with this database give the SQLSTATE[42P18]: Indeterminate datatype: 7 ERROR: could not determine data type of parameter $1; then i switched to mysql database with the same table structure and the md5(concat(‘hardsalt’,?,db_salt)) and it works like a charm.
In the pgsql pdo driver have a trouble, if i use only md5(?) with pdo_pgsql it works, but when i use the complex treatment it give me the error. where i can sent this bug?.
report issue here : https://github.com/zendframework/zf2/issues?state=open
[…] 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 […]
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
in Module.php, fill following functions with common functions of Module class.
i can’t understand this row, where is “flashmessenger()”, i can’t find it in AbstractController
‘messages’ => $this->flashmessenger()->getMessages()
it call controller plugin which automatically invoked via PluginManager, see : Zend\Mvc\Controller\PluginManager in $invokableClasses value.
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()?
because current storage doesn’t have rememberme functionality, so we re-set again.
and how can i get “username” within Storage
please look at the docs : http://zf2.readthedocs.org/en/latest/
Thanks, i running. i have updated my project to ZF 2.1.1, and Zend\Authentication\Storage doesn’t work, this message come with error
Container cannot write to storage due to type mismatch
do you have any idea
please clear your browser cache, re-start your web server, and try to run it again.
i clear my Chrome’s cache, restart my WAMP server, and my WAMP server does not run, 😦
based on this issue https://github.com/zendframework/zf2/issues/3623 it should be fixed with this PR : https://github.com/ralphschindler/zf2/commit/e0c7e46d6217967f50ba81482c82b165a1aa84e6 , I think you’ve run “dev” version of 2.1.1, I suggest to you to update again to the latest master ( 2.1.2 ), clear your browser cache, re-start your web server, or try another way, restart your computer ( last try 😀 ) 😉
thanks, i update to ZF 2.1.2 and it running
You’re welcome 😉
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.
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?
read this : https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/
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/
you should install by composer, so it automatically downloaded to vendor folder and automatically added to autoload
Ok thank, I’ m new in this the zend framework and i dont understand still, buy thanks.
Hi ! how do i do, for add more data the validation?, for example a keyword
user: name1;
pass: pass1;
keyword: dog;
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
read this : http://stackoverflow.com/questions/1871142/zend-framework-how-to-check-an-additional-column-while-using-dbtable-auth-adapt , modify to adapt ZF2
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
read this : https://samsonasik.wordpress.com/2012/08/23/zend-framework-2-controllerpluginmanager-append-controller-pluginto-all-controller/ , modify getSessContainer() function to get AuthService, see how to get ServiceLocator here : https://gist.github.com/samsonasik/3747836
This is great learning. Have you used ZfcUser? You could teach us how to use and expand it.
Yes, good idea, thanks.
How to get if user is logged in view like in zf1 zend_auth
see above comment : https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/#comment-4073
ok, thanks, i didn’t found it
here the username is not checked for case sensitivity. how can we check username is valid
i think it’s your db charset problem. see this : http://stackoverflow.com/questions/4413024/case-insensitive-unicode-collation-in-mysql
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());
because current storage (default) doesn’t have rememberme functionality, so we re-set again 😉
I thought it was set up in line 32 of Module.php.
I think I’m not understanding the router.
Sir how to get the id of logged in user. This id will be used in other table as foreign keys…
Thanks in advance
try :
it returning the username of logged in user instead of id..
you can get that after authenticate() process.
after getting the ‘id’, you should save to the session :
and, you can get it in another resource like the following :
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
you should check the column name from the db.
Very good work man….thank you!!!!
you’re welcome
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.
check your zf version, use latest version ( 2.1.3). the exception introduce in zf 2.1.0
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.
I think it’s your server problem. please see apache error log. and see if your httpd.conf already setting up properly.
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?
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.
Thank you very much for this, it was of great help!
you’re welcome 😉
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!
Sorry for my misspelling of your name samsonasik, I was rushing haha. Thanks again
try add :
at the end of Bootstrap.php
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?
create a class that extends Zend\Authentication\Adapter\DbTable and override _authenticateValidateResultSet() and _authenticateValidateResult() function and use at adapter for your AuthenticationService.
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,
you must be have whitespace somewhere, find it or fix them using php-cs-fixer.
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
grab from my github account : https://github.com/samsonasik/SanAuth
Hi!
Actually I forgotten to add autoload classmap file.
The application is working now. Can you add a tutorial on adding forms using annotatin builder?
Thanks
Sandesh Magdum
read this : https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/
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
you can read my other post : https://samsonasik.wordpress.com/2012/10/11/zend-framework-2-using-zend-form-and-ajax/
(sorry for the mistake in your name… I just saw the real spelling now)
i don’t know what you mean
that is what I see when I open ~/public/auth
it’s weird, just curious you miss one/more step ;).
I might..
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
read this : https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/
hello! thnks a lot for the code! i just want to know, where you have specified the database ? thnks in advance 🙂
in config/autoload/global.php and/or config/autoload/local.php, follow zf doc ! http://zf2.readthedocs.org/en/latest/user-guide/database-and-models.html
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.
salam…
use latest zf version.
wasalam
i am using latest version i was using mistakenly two files for database connectivity now problem resolved thanks for response.
you’re welcome 😉
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
if you’re using bcrypt, you should setSalt first to make it not re-generated every it called.
you can’t use that in constructor of DbTableAuthAdapter, use at setCredential function.
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?
$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 :
and use encrypted password to setCredential() function.
read the codex to post sourcecode http://en.support.wordpress.com/code/posting-source-code/
ok tyvm… although I dint understand you completely I got it working.. 😉
one more thing: can I get other values from db without fetching them manually?
like:
assign that to variable :
I am trying to get the data in Application’s IndexController
output: string(7) “musafar”
but, echo’ing throws “property of non-object” error and
output: bool(false)
use that at authenticate process only.
ok, I thought we are using a Session
ok I got what I want
Thanks for your help and thanks for such posts 🙂
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.
try something like this :
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’ );
Sorry, I should have pointed out that my post applies if you are using Doctrine to persist identity
I should give this in authenticate Method of the UserController sam??
i’m not familiar with bjyauthorize, but maybe you can try that in authenticateAction. just read stackoverflow about this : http://stackoverflow.com/questions/16053479/zfcuser-redirect-roles-to-different-pages-after-login 😉
okay cool sam, But may I know is there any other alternative way to achieve it? without using bjyauthorize?
I’ve create own module to achive this 😉
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!
good idea, thanks for the suggestion.
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
as early as possible please resolve the above issue
in Module.php, fill following functions with /*common code*/ functions of Module class.
btw, download complete example in http://github.com/samsonasik/SanAuth
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 🙂
read the docs : http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.identity.html#zend-view-helpers-initial-identity
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
if you call from view_helper, you should call by
thank you so much 🙂 and how to get the identity from it??
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
if you save passwords, you should have concensus of salt.
ok thanks
You’re welcome 🙂
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
look carefully, route name is ‘login’
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
Ignore my question, I figured it out
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
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
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 🙂
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
override module ? override service maybe :). override your service with allow_override option at your service manager registration.
If anybody interested on registration/login form for ZF2 https://github.com/xFran/TarSignup
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 🙂
you’re welcome 😉
If you want to take a great deal from this piece of writing then you have
to apply these methods to your won webpage.
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?.
The client side validations added for the Login form is not working in Internet explorer. Please comment or suggest for its alternative.
don’t use IE !
You are my Guru
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’);
it assign $this->authservice with the given service 😀
Hi….
I need some help regarding validation of username while registering user. While registering username should not take space. How it could be done???
use StringTrim filter
strpos did my work!!!!
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Module_App1
hosted with ❤ by GitHub
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Module_App2
hosted with ❤ by GitHub
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.
Try :
$this->getAuthService()->getStorage()->clear();
Thanks for the reply!!!
Little bit changes solved it.
$storage_name = $this->getAuthService()->getStorage()->getNamespace();
$this->getAuthService()->getStorage()->clear($storage_name);
Excellent, great!
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
$this->getAuthService()->getStorage()->read();
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
then you need to write the session value properly, print_r the data and break execution ( die; ) before write ->getStorage()->write($data);
Sorry i didn’t understand you’r solution can you get me the all function
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 ??
How to redirect to the previous page (url) after login ?
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. 😉
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.
try
i’m not on my front of pc right now, but hope inspire ^^
Thanks for your reply. It is giving this error
Cannot modify header information – headers already sent by and not getting redirected.
btw Eid Mubarak!!!!
it seems your php files not trimmed ( white space(s) ), try php-cs-fixer to fix them. thanks, happy ied mubarok to you too 🙂
used php cs-fixer but no luck!!!
PHP version for my server is 5.3.23. Can php version would be the problem????
i think you should check your apache error log, and see what happen…
Hi, It was server problem. According to you, which type of server would be suitable for Zend Framework applications.
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.
hi its really good work
really helpful for new learners.
please help me for creating database connection and in src/model/…php folder
read the docs http://zf2.readthedocs.org !
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
Connect Error: SQLSTATE[HY000] [1044] Access denied for user ”@’localhost’ to database ‘smb’
i have connect with database but i m getting this error
that must be your config problem, check your global.php and local.php, read the docs : http://zf2.readthedocs.org/en/latest/user-guide/database-and-models.html
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…
it’s using zend\db, your local.php doesn’t have zend\db config ( your config is doctine )… again, read the docs !!! http://zf2.readthedocs.org/en/latest/user-guide/database-and-models.html
ERROR CLEARED
but username and password are not storing in users table…
i m waiting for ur idea…
Tell Me the best tutorial to learn zend framework2 and doctrine2
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.
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 !
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
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…
read no 2 step properly, there is a link to https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/
how to add 2 or more submit button in same form like save cancel and exit
create only one submit, and double/more echo with change setValue() on the fly, and then check on the valid form.
how to add 2 or more submit button in same form like save cancel and exit using ZF2 and doctrine2
for cancel u need to put ‘reset’,
for exit u can use jquery…
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
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
Thank you
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.
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.
create your custom filter and apply to it.
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’,
),
),
),
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.
create your own filter
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..
read this for setting up layout variable : https://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
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);
}
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;
}
}
// 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…
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….
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….
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 ‘
‘;
});
}
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
finally I got the output…..thanks for u…
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…..
get the role of logged user, and add conditional for it. effort please 🙂
generate pdf document i’ll use Zendpdf to produce error and how to add a mapper to access the ZendPdf/PdfDocument in library
Put The correct name in your controller.. after that its works correctly..:)
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
where do you want to access it ? in view ? read this : https://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
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);
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
read the docs please https://zf2.readthedocs.org/en/latest/modules/zend.filter.writing-filters.html
$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…..
In zf2 form
datepicker is not working in ie and mozila….
tell me any other way how to do nu,
create your own custom element ! http://zf2.readthedocs.org/en/latest/modules/zend.form.advanced-use-of-forms.html#creating-custom-elements
please read the docs before ask
I need calendar in my date of birth and date of joining…
zend/form/element/date working in chrome alone….
again, create your custom form element, read the docs http://zf2.readthedocs.org/en/latest/modules/zend.form.advanced-use-of-forms.html#creating-custom-elements
thanks for ur help…I m learning lot from u…
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
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.
read this https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/ for how to get doctrine/common
Ok sir fine, and thanks for the response but now I just do not want to use doctrine/common, can you please help me out in getting my login form check the authentication of a user using AuthenticationService of ZF2…..
just create a form !!! please read the docs from the beginning user guide, there is a tutorial for form creation
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
please stop keep asking OOT comment on non-correlate post. or I will mark you as spam.
I m sorry…
Hey, trying to use your module, but get this error :
“A value for the identity was not provided prior to authentication with DbTable.”
Already fix by myself. Misstype one letter :). Thx for module.
hey…. bro 😦
i dont know understand this code easily
which is the model,controller and form
so please help me
[…] wollte nach diesem Tutorial ein einfaches Login erstellen, und da warf Zend Framework 2 mir diese 'hilfreiche' […]
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
check the route 🙂
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
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
you can do this :
you can check with list of controller(s)/action(s) when needed.
Thank you so much for your prompt reply. That would help me a lot. Much appreciated.
Dear Sam
what is “‘SanAuthWithDbSaveHandler\Controller\AuthController'”?
Hey sam,
how to override or redirect the 500 error in zend 2..? (Not using htaccess for redirection)..
https://samsonasik.wordpress.com/2012/09/19/zend-framework-2-create-custom-error-page/
‘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..?
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”
http://pastie.org/private/7dh6mdhmn02tncil77t5xg
look the stack trace, and you will found the issue
not getting any clues , getting start with zf2, link to the stack trace
http://pastie.org/8474499
$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,,
http://ikorolchuk.blogspot.com/2013/07/zend-framework-2-bcrypt-adapter-for.html
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
Please, what did you add on “if(!$result->isValid()) // Authentication failed”?
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.
the easiest way is add more conditional after it authenticated.
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) ?
create your custom adapter like this http://ikorolchuk.blogspot.com/2013/07/zend-framework-2-bcrypt-adapter-for.html
Thanks again Sam! Smells like a hell lot of work need to be done on road ahead 😀
Thanks Amazing tutorial
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?
http://lmgtfy.com/?q=zend%20framework%202%20setting%20db%20adapter
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?
itu session namespace, iya boleh 😀
Oo iya mas, barusan cek pakai print_r ternyata nama jadi nama index di $_SESSION. Terima kasih mas. Sukses selalu buat mas.
sip, Aamiin
How can i call the auth function in other modules
$this->getAuthService()->hasIdentity()
take a look the function. call via servicemanager, read https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
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.
you can create aliases of ‘AuthService’.
and check by identity view helper
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?
Thanks you very much!
Have a nice weekend!
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.
do something like this https://github.com/samsonasik/SanAuthWithDbSaveHandler/commit/e2ae4dfcebb7a952d7b1adaadcf6496c994423b9
thanks for the link!
another question: is there any way to get more information from the database, for example the real user name and his access level? Thanks!
read this docs http://zf2.readthedocs.org/en/latest/modules/zend.authentication.adapter.dbtable.html
Thanks! I only used the http://framework.zend.com/manual/2.2/en/index.html and some other web sources so far.. 🙂
[…] 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: […]
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???
https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/
Hi, thank you for your response.
Now i want to know: after authentification how to get user informations (ex: username)??
thank you …
see comment https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/#comment-4976
hi, it’s nice…
Maybe a silly question, but what is the best way to define Application wide constants/variables in ZF2?
Thanks!
global var is not recommended, but you can use servicemanager to be callable everywhere or use eventmanager to attach something, see https://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
that was fast, wow!
Thanks!
i got only 4 text box after running this code
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
thanks,
i set logout link at menubar,, but i want to set it enable when we are not logged in, how can i?
read the docs please http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.identity.html
[…] https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authen… […]
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.
you need to check if the page is authenticated page or not by eventManager globally by something like this : https://github.com/samsonasik/SanAuthWithDbSaveHandler/commit/e2ae4dfcebb7a952d7b1adaadcf6496c994423b9
thank you
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
thanks you, but you can give me full code? I can’t it.
read again the post, I have linked my github repo on it.
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
http://modules.zendframework.com/?query=mail
hi ! Mr Samsonasik
thank for this tutorial but i have any problem
it error DoctrineAnnotationParser.php
Hi, Samsonasik
If use Zend\Crypt\Password\Bcrypt to encrypt passwords, how to accurately AuthenticationService
help me !!
google please !!! http://lmgtfy.com?q=ZF2+bcrypt+adapter+authentication
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!
then you need to have album/auth/login.phtml under view folder.
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..
that’s session storage namespace, you can type other. please read the zf2 code
when I add “SanAuth” in config/application.config.php the app return a error 500. Can you help me please?
you need to have SanAuth module, you can grab here : https://github.com/samsonasik/SanAuth
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,
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.
I got it working!
Missed to import ” use Zend\Form\Annotation;” in User.php 🙂
Thanks for the quick response. Good Work. (y)
you’re welcome 😉
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
Ahh and I forgot, my User-Class needs the $dbAdapter. Is there any trick to give him the $dbAdapter without send it in the params like: new User($dbAdapter, $id);
please read it https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
“Save” at service, call at service, calling in all views should use view_helper or inject via eventmanager, read https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/ and https://samsonasik.wordpress.com/2013/03/30/zend-framework-2-getting-closer-with-eventmanager/ , for acl, find ‘acl’ via search box, and please read the official zf2 docs : zf2.readthedocs.org/en/latest/
hmm, okay. I can save it at service and view helper. In ZF1 I used Zend Registry. But allright. Thanks
[…] Create Simple Login Authentication Database Table […]
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?
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)
Thks for the article very useful.
you’re welcome 😉
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
please read https://samsonasik.wordpress.com/2012/10/04/zend-framework-2-step-by-step-build-form-using-annotation-builder/ and follow the blog post carefully 🙂
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
the ‘AuthService’ can be applied everywhere in other module. so you can for example, check in other module :
please read https://samsonasik.wordpress.com/2013/03/30/zend-framework-2-getting-closer-with-eventmanager/ for mvc event that can be applied with service manager
Thanks for your hint.
How can i register the AuthServer for the whole application?
The ZF is a complex framework. especially for beginners.
regards
Hans
once you already register the service, you can call anywhere, please read https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/ for service manager and again, please read again about https://samsonasik.wordpress.com/2013/03/30/zend-framework-2-getting-closer-with-eventmanager/ about eventmanager
It works. Many thanks for your help.
you’re welcome 😉
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.
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 !
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.
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…
Thanks for this; I really need a step by step tutorial. Your title looked promising, but I must move on.
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!
you can check rows after authenticate :
and check the results.
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.
@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?
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 🙂
Hi, it should be the field name is not registered in your form. please check case sensitive on it.
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. 🙂
great! 😉
[…] Create Simple Login Authentication Database Table […]
Hi, Samsonasik!
How can I use this
$this->getServiceLocator()
->get(‘AuthService’)->hasIdentity())
in view/layout?
Thanks for help!
see comment https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/#comment-6308
Thank you!
[…] Zend Framework 2 : Create Simple Login Authentication using … […]
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?
please tutorial to run this project.tks!
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
it require db adapter setting, please read the docs http://zf2.readthedocs.org/en/latest/user-guide/database-and-models.html
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
you need to add :
don’t be hurry to learn! and do effort!
i already added this in module.php
I’m trying change remember me param in auth_storage, but it doesn’t work.
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…………….
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
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 :
or
you may consult in apigility mailing list : https://groups.google.com/a/zend.com/forum/#!forum/apigility-users for the right approach ;).
whether we can changed the auth form design. if so how?
yes! use formRow() or formElement() view helper to do that! follow the docs http://zf2.readthedocs.org/en/latest/user-guide/forms-and-actions.html and http://zf2.readthedocs.org/en/latest/modules/zend.form.quick-start.html?highlight=formelement#rendering
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.
as default session object member name named ‘storage’, you can set other with create new methods in AuthStorage class, like this :
and you can set other member when doing set session write :
and if you want to call default ‘storage’ member, you can switch with setMember again :
Thanks
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!
if you need to inject, use factory, please read https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/ on factory section.
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
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’.
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
you probably need to force do :
on “
setRememberMe()
” method.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/
please read my servicemanager post https://samsonasik.wordpress.com/2013/01/02/zend-framework-2-cheat-sheet-service-manager/
Thanks Sam. I found this post 3 days ago and my already solved.
Anyways, Thank a lot
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!
ah, read this page – http://framework.zend.com/manual/current/en/modules/zend.authentication.adapter.dbtable.html one can just use CredentialTreatmentAdapter.
Still, updating the post or creating an updated one wouldn’t be bad, 🙂
thanks anyway!
yes, change to
Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter
.thanks!
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
do something like this https://github.com/samsonasik/SanAuthWithDbSaveHandler/commit/e2ae4dfcebb7a952d7b1adaadcf6496c994423b9 , collect resources that not needed in array/db-fetch 😉
Zend\Authentication\Adapter\DbTable was marked as deprecated
yes, use
Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter
insteadHi,
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
there is no Zend\Auth in ZF2 :P, it should be Zend\Authentication, you can use identity() view helper for that, check the documentation http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.identity.html
how do you retrieve the name of the user logged in? success?
use identity view helper, please read the docs http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.identity.html
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!
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’;
}
var_dump()
How can I do to retrieve user information logged in item (7. The success view) ?
Already thanks!
use Identity view helper, read the docs: http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.identity.html
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.
you may need create custom adapter, see my comment: https://samsonasik.wordpress.com/2012/10/23/zend-framework-2-create-login-authentication-using-authenticationservice-with-rememberme/#comment-6133
Thank you Sam for such helpful blog.
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)
please read the documentation: http://zf2.readthedocs.org/en/latest/modules/zend.session.config.standard-config.html?highlight=life
also, javascript is your task :), just check checker on background that check the idle, google is your friend 😉
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.
you should not pull servicelocator from controller, build controller using factory instead.
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.
You can create authentication adapter for it. For example:
So, you can define your `AuthenticationService` via factory:
Then, register it:
So, in auth controller, you can do:
Dear samsonasik, thank you for your wonderful authentication module, i have sucessfully used it, and it is working very very well. My heartfelt thanks for your kind contribution. Now i wanted to validate the user against OpenLDAP server, using your everything, except the it should query the ldap server, and then get the user field, just like you did with a mysql table, can you please quite me as to how to do it for openldap server, where the username and password is, thanks a lot.
I have no idea about ldap right now
Thank you…
Nice Tutorial
[…] Zend Framework 2 : Create Simple Login Authentication … […]
[…] Zend Framework 2 : Create Simple Login Authentication … […]
[…] » Visit Now Oct 23, 2012 · Zend Framework 2 : Create Simple Login Authentication using AuthenticationService with rememberMe. 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 … […]