CodeIgniter 4 Shield Authentication (Ultimate Guide)🔒

Reading Time: 6 minutes
2 Views

When it comes to modern PHP authentication, CodeIgniter 4 Shield is one of the most robust, flexible, and secure solutions for managing user authentication systems. It’s an official CodeIgniter 4 authentication library designed to handle registration, login, logout, password reset, and more, out of the box.

In this guide, we’ll cover how to install, configure, and implement CodeIgniter 4 Shield Authentication in our application.

Let’s get started.

Read More: How to Create CodeIgniter 4 Custom Helpers ✅

⚪ What is CodeIgniter 4 Shield?

Shield is a dedicated authentication and authorization package created for CodeIgniter 4. It provides a clean, structured way to manage user sessions, roles, permissions, and security mechanisms with minimal setup.

Key Features:

  • User registration and login
  • Password hashing and reset workflows
  • Role-based access control
  • Secure session management
  • Easy customization for your application’s needs

⚪ Installing CodeIgniter Shield

To begin integrating Shield into your CodeIgniter 4 project, we’ll install it via Composer.

Install Shield via Composer:

composer require codeigniter4/shield

After installation, we’ll need to publish the configuration files to your app/Config directory, so you can customize authentication settings later.

Publish its configuration files:

php spark shield:publish

⚪ Running Database Migrations

Once Shield is installed, it requires several database tables to manage users, tokens, and login attempts.

By running php spark migrate, CodeIgniter will create these necessary tables automatically.

Command,

php spark migrate

⚪ Setting Up Routes

To handle registration, login, logout, and dashboard pages, you need to define appropriate routes in app/Config/Routes.php file.

Open file and add these routes,

$routes->group('auth', ['namespace' => 'App\Controllers'], function ($routes) {
    $routes->get('login', 'AuthController::login');
    $routes->post('login', 'AuthController::attemptLogin');
    $routes->get('register', 'AuthController::register');
    $routes->post('register', 'AuthController::attemptRegister');
    $routes->get('logout', 'AuthController::logout');
});

$routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);

⚪ Creating Authentication Controllers

We’ll create an AuthController to handle the business logic for user registration, login, and logout actions.

To create AuthController.php inside app/Controllers/, run this Spark CLI command from project terminal,

php spark make:controller Auth --suffix

We can now open this file and start adding your methods like register(), attemptRegister(), login(), attemptLogin(), and logout().

<?php
namespace App\Controllers;

use CodeIgniter\Shield\Authentication\Authentication;
use CodeIgniter\Shield\Entities\User;
use CodeIgniter\Shield\Models\UserModel;
use CodeIgniter\Controller;

class AuthController extends Controller
{
    public function register()
    {
        return view('auth/register');
    }

    public function attemptRegister()
    {
        $users = new UserModel();
        $data = [
            'username' => $this->request->getPost('username'),
            'email'    => $this->request->getPost('email'),
            'password' => $this->request->getPost('password')
        ];

        if ($users->insert($data)) {
            return redirect()->to('/auth/login')->with('success', 'Registration Successful. Please login.');
        }

        return redirect()->back()->with('error', 'Registration failed.');
    }

    public function login()
    {
        return view('auth/login');
    }

    public function attemptLogin()
    {
        $auth = service('authentication');

        $credentials = [
            'email'    => $this->request->getPost('email'),
            'password' => $this->request->getPost('password')
        ];

        if ($auth->attempt($credentials)) {
            return redirect()->to('/dashboard');
        }

        return redirect()->back()->with('error', 'Invalid login credentials.');
    }

    public function logout()
    {
        service('authentication')->logout();
        return redirect()->to('/auth/login')->with('success', 'Logged out successfully.');
    }
}

and Also we need dashboard,

php spark make:controller Dashboard

Add these codes into Dashboard.php file,

<?php
namespace App\Controllers;

use CodeIgniter\Controller;

class Dashboard extends Controller
{
    public function index()
    {
        return view('dashboard');
    }
}

⚪ Protecting Routes with Filters

Shield uses filters to restrict access to specific parts of your application.

Here, we’ll register Shield’s SessionAuth filter in app/Config/Filters.php and apply it to routes like the dashboard. This ensures only authenticated users can view protected pages, enforcing access control effectively.

📍 In app/Config/Filters.php:

public $aliases = [
    'auth' => \CodeIgniter\Shield\Filters\SessionAuth::class,
];

⚪ Creating Views

To make the authentication system functional and user-friendly, simple views for registration, login, and the dashboard are created.

📍 In app/Views/auth/register.php,

<h2>Register</h2>
<form method="post" action="<?= site_url('auth/register') ?>">
    <input type="text" name="username" placeholder="Username"><br>
    <input type="email" name="email" placeholder="Email"><br>
    <input type="password" name="password" placeholder="Password"><br>
    <button type="submit">Register</button>
</form>

📍 In app/Views/auth/login.php,

<h2>Login</h2>
<form method="post" action="<?= site_url('auth/login') ?>">
    <input type="email" name="email" placeholder="Email"><br>
    <input type="password" name="password" placeholder="Password"><br>
    <button type="submit">Login</button>
</form>

📍 In app/Views/dashboard.php,

<h2>Welcome to the Dashboard!</h2>
<p>You are logged in.</p>
<a href="<?= site_url('auth/logout') ?>">Logout</a>

⚪ Conclusion

In simple words — this tutorial showed how to set up login, registration, and logout using CodeIgniter 4 Shield. We installed Shield, created user tables, added routes, built controllers and views, and protected pages for logged-in users only. It makes adding secure user authentication easy in any CodeIgniter 4 project.

Now you can quickly build apps with safe login systems without worrying about complex security code!