Codeigniter 4 Packages: CI Shield

post Main Image

Part 1: from nothing to a protected page like a boss.

This step by step tutorial walks you through creating a minimal authentication system using CodeIgniter Shield, the official authentication and authorization library for CodeIgniter 4. On this part, we'll cover installation, setup, login/logout flow and protected routes and we go from nothing to a protected page.

Starting from a fresh CI4 install (and assuming you have a database connection that is setup and working already).

Step 1: Install and set up shield

composer require codeigniter4/shield
php spark shield:setup


Step 2: Create a protected page and view

Create app/Controllers/Dashboard.php: (use the spark-make controller DashboardController command - shameless plug to my own tool) and add

namespace App\Controllers;
use CodeIgniter\Controller;
class DashboardController extends Controller
{
    public function index()
    {
        return view('dashboard_view');
    }
}
Create a Views/dashboard_view.php file and add these contents (add your own html header, body and the rest)

this is the dashboard protected view <a href="<?= site_url('logout') ?>">Logout</a>


Step 3: Check your app/Config/Routes.php file

Ensure you have these lines on it:

service('auth')->routes($routes);
$routes->get('/', 'DashboardController::index');

$routes->get('dashboard', 'DashboardController::index');


Step 4: Ensure the login filter is applied to all routes by default

Apply to all routes, specify exclusions only on the app/Config/Filters.php file

public array $globals = [
        'before' => ['session' => ['except' => ['login*', 'register', 'auth/a/*', 'logout']],
]


Step 5: Create an initial user

On the command line, using spark

spark shield:user create

and enter 

Username : testuser2
Email : test@test.com
Password : secret123
Password confirmation : secret123
User "testuser2" created


Step 6: Test it

  1. Navigate to https://yoursite.com/dashboard, you should see the login page
  2. You can then log in at /login using: Email: test@test.com Password: secret123 
  3. Once you do you should be sent to your protected view where you can try to logout and then back in again.
  4. Rejoice on how good you are.


More

There is more to the shield than this. I'll explore more features at a later time.