Zend Authentication

Zend Authentication (Laminas Authentication) — Complete Guide

Zend Authentication (now called Laminas Authentication) is a component that provides a flexible and extensible way to authenticate users in PHP applications.


What Is Zend Authentication?

Laminas Authentication allows you to:

  • Check identity (like a username or email)
  • Validate credentials (like a password)
  • Store authentication results in a session or other storage

It is decoupled from specific storage mechanisms (e.g., DB, LDAP) and uses adapters.


1. Installation laminas-db

Make sure you have Laminas DB component installed Link


2. Installation laminas-authentication

Install Laminas Authentication and DB adapter:

composer require laminas/laminas-authentication

3. Database Table Structure (MySQL)

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(50) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL
);

4. Create Registration and Authentication Logic (module\Application\src\Controller\AuthController.php)

namespace Application\Controller;

use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\View\Model\ViewModel;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Sql\Sql;
use Laminas\Authentication\AuthenticationService;

class AuthController extends AbstractActionController
{
    protected $dbAdapter;

    public function __construct(Adapter $dbAdapter)
    {
        $this->dbAdapter = $dbAdapter;
    }

    public function registerAction()
    {
        if ($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $username = $data['username'];
            $password = password_hash($data['password'], PASSWORD_DEFAULT);

            $sql = new Sql($this->dbAdapter);
            $insert = $sql->insert('users')->values([
                'username' => $username,
                'password' => $password,
            ]);
            $statement = $sql->prepareStatementForSqlObject($insert);
            $statement->execute();

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

        return new ViewModel(); // register.phtml
    }

    public function loginAction()
    {
        $error = null;

        if ($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $password = $data['password'];
            $sql = new Sql($this->dbAdapter);
            $select = $sql->select();
            $select->from('users')
                ->where(['username' => $data['username']]);
            $statement = $sql->prepareStatementForSqlObject($select);
            $result = $statement->execute()->current();
            if ($result && password_verify($password, $result['password'])) {
                $auth = new AuthenticationService(); // Create authentication instance
                unset($result['password']); // remove password for security
                $auth->getStorage()->write((object)$result); // Register user data after get getIdentity()
                return $this->redirect()->toRoute('dashboard');
            } else {
                $error = "Invalid email/username or password.";
            }
        }

        return new ViewModel(['error' => $error]); // login.phtml
    }

    public function logoutAction()
    {
        $authService = new AuthenticationService();
        $authService->clearIdentity();   // Clear autentication session
        return $this->redirect()->toRoute('login');
    }

    public function dashboardAction()
    {
        $authService = new AuthenticationService();
        if (!$authService->hasIdentity()) {  // Check autentication user
            return $this->redirect()->toRoute('login');
        }

        $user = $authService->getIdentity();  // Get autentication user
        return new ViewModel(['user' => $user]); // dashboard.phtml
    }
}

5. Routing (module.config.php) (module\Application\config\module.config.php)

namespace Application;

use Laminas\Router\Http\Literal;
use Application\Controller\AuthController;

return [
    'router' => [
        'routes' => [
            'login' => [
                'type' => Literal::class,
                'options' => [
                    'route' => '/login',
                    'defaults' => [
                        'controller' => AuthController::class,
                        'action' => 'login',
                    ],
                ],
            ],
            'register' => [
                'type' => Literal::class,
                'options' => [
                    'route' => '/register',
                    'defaults' => [
                        'controller' => AuthController::class,
                        'action' => 'register',
                    ],
                ],
            ],
            'logout' => [
                'type' => Literal::class,
                'options' => [
                    'route' => '/logout',
                    'defaults' => [
                        'controller' => AuthController::class,
                        'action' => 'logout',
                    ],
                ],
            ],
            'dashboard' => [
                'type' => Literal::class,
                'options' => [
                    'route' => '/dashboard',
                    'defaults' => [
                        'controller' => AuthController::class,
                        'action' => 'dashboard',
                    ],
                ],
            ],
        ],
    ],
]



6. Add Controller Factory (module.config.php) (module\Application\config\module.config.php)

use Laminas\Db\Adapter\Adapter;

'controllers' => [
    'factories' => [
        AuthController::class => function($container) {
            return new AuthController(
                $container->get(Adapter::class)
            );
        }
    ],
],



6. Views

register.phtml (module\Application\view\application\auth\register.phtml)

<h2>Register</h2>
<form method="post">
    Username: <input type="text" name="username"><br><br>
    Password: <input type="password" name="password"><br><br>
    <button type="submit">Register</button>
</form>


login.phtml (module\Application\view\application\auth\login.phtml)

<h2>Login</h2>
<?php if ($this->error): ?>
    <p style="color:red"><?= $this->error ?></p>
<?php endif; ?>
<form method="post">
    Username: <input type="text" name="username"><br><br>
    Password: <input type="password" name="password"><br><br>
    <button type="submit">Login</button>
</form>


dashboard.phtml (module\Application\view\application\auth\dashboard.phtml)

<h2>Welcome <?= $this->user->username ?></h2>
<a href="/logout">Logout</a>

Done! You Have:

Feature

Route

Registration

/register

Login

/login

Logout

/logout

Dashboard

/dashboard


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.