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).
composer require codeigniter4/shield
php spark shield:setupStep 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 ControllerCreate a Views/dashboard_view.php file and add these contents (add your own html header, body and the rest)
{
public function index()
{
return view('dashboard_view');
}
}
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');
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
There is more to the shield than this. I'll explore more features at a later time.