Zend 2 Auth with Bcrypt?

Google does not have a lot of solutions (a similar question, but no answer).

Because bcrypt generates a new hash every time, authentication fails. I looked at the code (maybe the class itself), but it's pretty dirty (I would prefer my own solution). How can I use $bcrpt->verify() with $identity->isValid() ?

Edit: So far, I have subclassed the DbTable authentication class, and it works, but I very much doubt that it is optimized / "completely right." Still looking for an β€œelegant” solution.

+4
source share
3 answers

As you should know, BCrypt hashing uses salt. And this salt is generated again randomly every time. This greatly increases the difficulty of finding all passwords if your database is compromised. This way it will generate a new hash every time.

My own solution to the problem you are facing has its own Zend\Authentication adapter, which will retrieve the user model from the database (using username / email address) and then call $user->checkPassword($credential); . This method will get an instance of Zend\Crypt\Password\Bcrypt . Which would just call $bcrypt->verify() with a given password and hash in the user model.

+4
source

You can use:

 Zend\Authentication\Adapter\DbTable\CallbackCheckAdapter 

Like this:

 use Zend\Authentication\Adapter\DbTable\CallbackCheckAdapter as AuthAdapter; use Zend\Crypt\Password\Bcrypt; $credentialValidationCallback = function($dbCredential, $requestCredential) { return (new Bcrypt())->verify($requestCredential, $dbCredential); }; $authAdapter = new AuthAdapter($dbAdapter, 'user', 'login', 'password', $credentialValidationCallback); // ... 
+14
source

I did it like this (test code and it works) ..;

 if ($request->isPost()) { $form->setData($request->getPost()); if ($form->isValid()) { $bcrypt = new Bcrypt(); $user = new User(); $user->exchangeArray($form->getData()); $password = $user->password; $data = $this->getUserTable()->selectUser($user->username); if (!$data) { echo 'user not found'; } else { if ($bcrypt->verify($password, $data->hash)) { $sm = $this->getServiceLocator(); $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $authAdapter = new AuthAdapter( $dbAdapter, 'cms_users', 'username', 'hash' ); $authAdapter->setIdentity($user->username) ->setCredential($data->hash); $result = $auth->authenticate($authAdapter); echo $result->getIdentity() . "\n\n"; // do you thing on succes/failure } else { echo 'invalid password'; } } } } 
+1
source

All Articles