PHPackages                             rafaelwendel/ci4auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. rafaelwendel/ci4auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

rafaelwendel/ci4auth
====================

Basic Auth lib for managing authentication and authorization in the CodeIgniter 4 framework.

0.0.1(1mo ago)12MITPHPPHP ^8.0

Since Jun 13Pushed 1mo agoCompare

[ Source](https://github.com/rafaelwendel/CI4Auth)[ Packagist](https://packagist.org/packages/rafaelwendel/ci4auth)[ Docs](https://github.com/rafaelwendel/CI4Auth)[ RSS](/packages/rafaelwendel-ci4auth/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

CI4Auth
=======

[](#ci4auth)

[![Latest Version on Packagist](https://camo.githubusercontent.com/028ad00743a9e252b7a8e0431984c1a9de3b64022370f2c8ec5aa03b69c46760/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72616661656c77656e64656c2f636934617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rafaelwendel/ci4auth)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![PHP Version Require](https://camo.githubusercontent.com/23d185d525f163fc848f019029815f96e8ef3ff225f3db81b14a9ed18339e74d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e302d626c75652e7376673f7374796c653d666c61742d737175617265)](https://php.net)[![CodeIgniter 4 Support](https://camo.githubusercontent.com/75bb41bd19902feccc6faeb9593b69b24c7ef65291b26b8fbb5e1c0106d97fc1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f646569676e697465722d76342e782d6f72616e67652e7376673f7374796c653d666c61742d737175617265)](https://codeigniter.com)

**CI4Auth** is a lightweight, secure, and highly flexible authentication and authorization library specifically designed for the **CodeIgniter 4** framework. It helps you seamlessly manage user logins, sessions, and role-based access control (RBAC) on your routes with minimal setup.

---

Features
--------

[](#features)

- **Quick Installation**: Spark command to set up the configuration instantly.
- **Flexible Configuration**: Map database user properties to session keys dynamically.
- **Auto-Discovery**: Automatic service registration (`service('auth')`) and filter registration (`auth`).
- **Role-Based Access Control**: Simple filter integration in routes to restrict pages based on user roles.
- **Translation Support**: Out-of-the-box translations in English and Portuguese (Brazil), customizable in the main app.
- **Session Control**: Option to destroy the complete session on logout or only remove authentication data.

---

Requirements
------------

[](#requirements)

- PHP 8.0 or higher
- CodeIgniter 4.1.0 or higher

---

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

Install the package using Composer inside your CodeIgniter 4 project root:

```
composer require rafaelwendel/ci4auth
```

### 2. Publish the Configuration

[](#2-publish-the-configuration)

Run the Spark command to publish the default configuration template file to your application's config directory:

```
php spark auth:install
```

This will copy the configuration template to `app/Config/AuthConfig.php`.

---

Configuration (`AuthConfig.php`)
--------------------------------

[](#configuration-authconfigphp)

Open the newly published `app/Config/AuthConfig.php` file. You can override any default properties by uncommenting them.

Here is a summary of the configuration properties:

PropertyTypeDefault ValueDescription`$authModel``string``'App\Models\UserModel'`The fully qualified class name of the User Model.`$findUserMethod``string``'findUser'`The method in the User Model used to search for the user (by email, username, etc.).`$passwordField``string``'password'`The database table column or object property that holds the hashed password.`$sessionAuthCheckKey``string``'islogged'`The session key used to check if the user is authenticated.`$enableRoles``bool``false`Set to `true` to enable role-based access control (RBAC).`$roleKey``string``''`The session key representing the user's role (e.g. `'role'`, `'profile'`). Required if `$enableRoles` is `true`.`$sessionData``array`See templateA key-value map of data to be saved to the session on successful login. Use `'user.field'` format to map fields from the user record.`$destroySessionOnLogout``bool``false`If `true`, calls `$session->destroy()` on logout; if `false`, only removes `$sessionData` keys.`$notAuthenticatedRedirect``string``'login'`The route or URL path to redirect unauthenticated users.`$notAuthorizedRedirect``string``'login'`The route or URL path to redirect users with insufficient role permissions.### Example Mapping configuration:

[](#example-mapping-configuration)

```
namespace Config;

use CI4Auth\Config\BaseAuthConfig;

class AuthConfig extends BaseAuthConfig
{
    public string $authModel = 'App\Models\UserModel';
    public string $findUserMethod = 'findUser';
    public string $passwordField = 'password';

    public string $sessionAuthCheckKey = 'logged_in';
    public bool $enableRoles = true;
    public string $roleKey = 'user_role';

    public array $sessionData = [
        'logged_in' => true,
        'user_id'   => 'user.id',
        'user_email'=> 'user.email',
        'user_role' => 'user.role' // Required since enableRoles is true
    ];

    public bool $destroySessionOnLogout = false;
    public string $notAuthenticatedRedirect = 'auth/login';
    public string $notAuthorizedRedirect = 'dashboard/unauthorized';
}
```

---

Usage Guide
-----------

[](#usage-guide)

### 1. Setting Up Your User Model

[](#1-setting-up-your-user-model)

Your User Model (e.g., `App\Models\UserModel`) must contain the method specified in `$findUserMethod` (default `findUser`). This method must return the user record as an **object** or an **associative array** matching the credentials identity (e.g., email or username).

```
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['email', 'password', 'role', 'name'];

    /**
     * Finds a user by their identity (email)
     *
     * @param string $identity
     * @return array|object|null
     */
    public function findUser(string $identity)
    {
        return $this->where('email', $identity)->first();
    }
}
```

### 2. User Authentication (Login)

[](#2-user-authentication-login)

In your Login Controller, check the user's credentials using the `AuthService` (which is auto-registered as a service).

```
namespace App\Controllers;

class AuthController extends BaseController
{
    public function login()
    {
        $authService = service('auth');

        if ($this->request->is('post')) {
            $email    = $this->request->getPost('email');
            $password = $this->request->getPost('password');

            // Attempt authentication
            if ($authService->login($email, $password)) {
                return redirect()->to('dashboard')->with('success', 'Welcome back!');
            }

            // Authentication failed
            return redirect()->back()->with('error', 'Invalid email or password.');
        }

        return view('login_view');
    }
}
```

### 3. User Logout

[](#3-user-logout)

To log out the user, call the `logout()` method. It automatically removes the keys defined in `$sessionData` (or destroys the session if configured) and sets a localized flash message with the key `logout_message`.

```
namespace App\Controllers;

class AuthController extends BaseController
{
    public function logout()
    {
        service('auth')->logout();

        // Redirect to login page
        return redirect()->to('login')->with('success', session()->getFlashdata('logout_message'));
    }
}
```

---

Authorization &amp; Route Protection
------------------------------------

[](#authorization--route-protection)

You can protect your application routes using the auto-discovered **`AuthFilter`** (aliased as `'auth'`).

### Protecting Routes (No Roles)

[](#protecting-routes-no-roles)

To protect a group of routes so that only authenticated users can access them, apply the `'auth'` filter in your `app/Config/Routes.php` file:

```
$routes->group('dashboard', ['filter' => 'auth'], function($routes) {
    $routes->get('/', 'DashboardController::index');
    $routes->get('profile', 'DashboardController::profile');
});
```

### Protecting Routes with Role Authorization

[](#protecting-routes-with-role-authorization)

If `$enableRoles` is set to `true` in your configuration, you can pass authorized roles to the filter by appending them as arguments (separated by commas):

```
// Only users with 'admin' role can access the administration panel
$routes->get('admin/settings', 'AdminController::settings', ['filter' => 'auth:admin']);

// Users with either 'admin' OR 'manager' roles can access reports
$routes->group('reports', ['filter' => 'auth:admin,manager'], function($routes) {
    $routes->get('/', 'ReportsController::index');
    $routes->get('export', 'ReportsController::export');
});
```

When a user tries to access a restricted route without the appropriate role, they are redirected to the route defined by `$notAuthorizedRedirect` with an error message stored in the `error` flashdata key.

---

Localization &amp; Custom Messages
----------------------------------

[](#localization--custom-messages)

CI4Auth comes with preloaded language files for Portuguese (Brazil) and English.

If you wish to customize these messages (for example, formatting flash alerts), you can override them by creating a file named `Auth.php` inside your own application directories:

- `app/Language/en/Auth.php`
- `app/Language/pt-BR/Auth.php`

Return an array containing only the keys you wish to override:

```
// Example: app/Language/en/Auth.php
return [
    'logoutFlashMessage'           => 'You have successfully signed out.',
    'notAuthenticatedFlashMessage' => 'Access denied. Please sign in first.',
    'notAuthorizedFlashMessage'    => 'You do not have the required permissions to view this resource.',
];
```

---

License
-------

[](#license)

This library is open-source software licensed under the [MIT License](LICENSE).

###  Health Score

33

—

LowBetter than 72% of packages

Maintenance90

Actively maintained with recent releases

Popularity4

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity28

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

45d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/2855089?v=4)[Rafael Pinheiro](/maintainers/rafaelwendel)[@rafaelwendel](https://github.com/rafaelwendel)

---

Top Contributors

[![rafaelwendel](https://avatars.githubusercontent.com/u/2855089?v=4)](https://github.com/rafaelwendel "rafaelwendel (11 commits)")

---

Tags

phpauthAuthenticationauthorizationcodeigniter4

### Embed Badge

![Health badge](/badges/rafaelwendel-ci4auth/health.svg)

```
[![Health](https://phpackages.com/badges/rafaelwendel-ci4auth/health.svg)](https://phpackages.com/packages/rafaelwendel-ci4auth)
```

###  Alternatives

[league/oauth2-server

A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.

6.7k147.0M304](/packages/league-oauth2-server)[auth0/auth0-php

PHP SDK for Auth0 Authentication and Management APIs.

41121.9M94](/packages/auth0-auth0-php)[auth0/symfony

Symfony SDK for Auth0 Authentication and Management APIs.

128814.6k](/packages/auth0-symfony)[kinde-oss/kinde-auth-php

Kinde PHP SDK for authentication

2287.5k3](/packages/kinde-oss-kinde-auth-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
