Here are the key steps:
- Create the factory for the authentication service.
namespace MyModule;
use Interop\Container\ContainerInterface;
use Zend\Authentication\Adapter\DbTable\CredentialTreatmentAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Db\Adapter\AdapterInterface;
use Zend\ServiceManager\Factory\FactoryInterface;
class AuthenticationServiceFactory implements FactoryInterface
{
public function __invoke(
ContainerInterface $container,
$requestedName,
array $options = null
) {
// Database adapter
/** @var \Zend\Db\Adapter\Adapter $dbAdapter */
$dbAdapter = $container->get(AdapterInterface::class);
// Auth adapter
$authAdapter = new CredentialTreatmentAdapter(
$dbAdapter,
'users', // table name
'username', // identity column
'password', // credential column
'SHA1(?)' // credential treatment
);
return new AuthenticationService(null, $authAdapter);
}
}
- Register the factory:
'service_manager' => [
'factories' => [
Zend\Authentication\AuthenticationServiceInterface::class => MyModule\AuthenticationServiceFactory::class,
],
],
Then use it in your controller for login:
public function loginAction()
{
// …
if ($this->getRequest()->isPost()) {
// Get form data…
// Get authentication service
/** @var \Zend\Authentication\AuthenticationService $authenticationService */
$authenticationService = $this->plugin('identity')->getAuthenticationService();
// Set identity and credential for auth service
/* @var $adapter \Zend\Authentication\Adapter\DbTable\AbstractAdapter */
$adapter = $authenticationService->getAdapter();
$adapter->setIdentity($data['location'])
->setCredential($data['password']);
// Validation
if ($authenticationService->authenticate()->isValid()) {
// Get result
/** @var \Zend\Authentication\Storage\Session $storage */
$storage = $authenticationService->getStorage();
$result = $adapter->getResultRowObject(
[
'id',
'roleid',
'username',
'nickname',
]
);
// Create user
$user = new User($result->id);
// Write to session
$storage->write($user);
// Redirect…
}
}
// …
}
and logout:
public function logoutAction()
{
// Has identity?
if (! $this->identity()) {
return $this->redirect()->toRoute('…');
}
// Get authentication service
/** @var \Zend\Authentication\AuthenticationService $authenticationService */
$authenticationService = $this->plugin('identity')->getAuthenticationService();
// Clear identity
$authenticationService->clearIdentity();
// Set success message
$this->flashMessenger()->addSuccessMessage('Logout successful…');
return $this->redirect()->toRoute('…');
}
And in your view scripts:
var_dump($this->identity()); // User::class (after login)
Attention
The above code has not been tested, it only shows the main process and needs to be customized!