CodeIgniter Shield Documentation

repository·develop·Indexed 19 days ago

https://github.com/codeigniter4/shield

The official authentication and authorization framework for CodeIgniter 4. Shield provides tools for managing users, sessions, tokens, and permissions, supporting multiple authentication strategies including session-based, Access Tokens, HMAC SHA256 Tokens, and JSON Web Tokens (JWT). Key features include email verification, two-factor authentication (2FA), magic link account recovery, and groups-based access control.

Tokens
42.2K
Snippets
170
Records
198
Agent score
64%

What's inside CodeIgniter Shield

  1. Overview of CodeIgniter Shield features

    develop

    CodeIgniter Shield is the official authentication and authorization framework for CodeIgniter 4. It provides a flexible, security-focused foundation that can be extended or overridden to meet specific application needs.

    Supported Authentication Methods

    • Session-based Authentication: Traditional ID/Password login with 'Remember-me' functionality.
    • Stateless Authentication: Supports Access Token, HMAC SHA256 Token, or JWT (JSON Web Token).

    Key Security and Access Control Features

    • Two-Factor Authentication (2FA): Optional email-based 2FA after login.
    • Email Verification: Optional verification during account registration.
    • Magic Link Login: Allows users to log in via email if they forget their password.
    • Access Control: Uses flexible Group-based Access Control (similar to Roles) and individual Permissions.

    Extensibility and Integration

    • User Management: Includes a ready-to-use User Entity and User Provider (UserModel).
    • Settings: Integrates with the CodeIgniter settings library, allowing configuration to be stored in version control or updated in the database.
    • Customization: Provides easily extendable controllers and views that can be swapped out for custom implementations.
    • Auth Helper: A simple helper is provided for common authentication actions.
  2. Key features of CodeIgniter Shield

    develop

    Shield provides a comprehensive suite of security features out of the box:

    • Authentication: Session-based (with Remember-me) and stateless Personal Access Tokens.
    • Verification & MFA: Optional email verification during registration and optional email-based Two-Factor Authentication (2FA) after login.
    • Account Recovery: Magic Link Login for password recovery.
    • Authorization: Flexible Groups-based access control (similar to Roles) and the ability to grant specific individual Permissions to users.
  3. Available Authenticators in CodeIgniter Shield

    develop

    Shield supports several authentication strategies depending on your application type (traditional web apps vs. stateless APIs). You can choose from the following built-in authenticators:

    • Session: Traditional ID/Password authentication. It validates credentials (username, email, or password) and persists user information in the server-side session.
    • AccessTokens: Stateless authentication designed for APIs. It uses Personal Access Tokens passed via HTTP headers.
    • HmacSha256: Stateless authentication using HMAC Keys for secure API communication.
    • JWT: Stateless authentication using JSON Web Tokens (requires additional setup).

    Beyond these defaults, you can implement the AuthenticatorInterface to create Custom Authenticators for project-specific logic like external providers or hardware challenges.

  4. Overview of CodeIgniter Shield authentication methods

    develop

    Shield supports several authentication strategies depending on your application's needs:

    • Session-based: Traditional email/username and password authentication. Includes secure "remember-me" functionality and comes with controllers and views for registration, login, and password recovery. Ideal for standard web applications.
    • Access Token: Stateless authentication where users can have multiple unique tokens (similar to GitHub tokens). Best for third-party API access or mobile applications.
    • HMAC SHA256 Token: An advanced version of Access Token authentication. Instead of passing a secret key in the request, a shared secret is used to create a hash signature of the request body, increasing security.
    • JSON Web Token (JWT): A compact, self-contained method for securely transmitting information as a JSON object, commonly used for web application authentication and authorization.
  5. Configure Role-Based Access Control (RBAC) in Shield

    develop

    Shield uses a flexible RBAC system where users can belong to multiple groups. Groups act as roles (e.g., admin, user), and permissions can be assigned to these groups or directly to individual users.

    To configure your authorization system, you must edit Config\AuthGroups to define:

    1. Groups: The available roles.
    2. Default Group: The group assigned to new registrants.
    3. Permissions: The specific actions available in the system.
    4. Matrix: The mapping of permissions to groups.
    // Config\AuthGroups.php
    
    public array $groups = [
        'superadmin' => [
            'title'       => 'Super Admin',
            'description' => 'Optional description of the group.',
        ],
    ];
    
    public string $defaultGroup = 'user';
    
    public array $permissions = [
        'admin.access'        => 'Can access the sites admin area',
        'users.create'        => 'Can create new non-admin users',
        'beta.access'         => 'Can access beta-level features'
    ];
    
    public array $matrix = [
        'admin' => [
            'admin.access',
            'users.create',
            'beta.access'
        ],
    ];
  6. Assign and check Token Permissions (Scopes)

    develop

    Access tokens can be assigned specific scopes (permission strings) to limit what the token can do on the API, regardless of the user's overall permissions. If no scopes are specified during generation, the token is granted access to all scopes.

    Note: Avoid using colons (:) in scope names, as this can interfere with route filter recognition.

    To check if a token has a specific permission during a request, use the tokenCan() method on the user entity.

    // Generating a token with a specific scope
    return $user->generateAccessToken('token-name', ['users-read'])->raw_token;
    
    // Checking for a scope in your logic
    if ($user->tokenCan('users-read')) {
        //
    }
  7. How Gateway Actions work for multiple verification methods

    develop

    A Gateway Action is a single custom action used to manage multiple possible verification methods (e.g., choosing between Email or SMS 2FA). Instead of registering multiple actions for login, you register one 'Gateway' action.

    Implementation details:

    1. Conditionality: The gateway can implement ConditionalActionInterface to check if the user has any supported identity (e.g., return $user->getIdentity('mfa_email') !== null || $user->getIdentity('mfa_sms') !== null;).
    2. Lifecycle:
      • show(): Displays the available methods to the user.
      • handle(): Validates the user's choice, sends the challenge, and remembers the selected method.
      • verify(): Verifies the challenge.
    3. Identity Type: The gateway must return a single action identity type via getType() (e.g., mfa_gateway). Do not create separate identities for each sub-method.
    4. State: Use the extra value of the identity for the pending action message. Store internal gateway state (like the selected method) in other identity fields (like secret2) or application-owned tables.
  8. How User Identities work

    develop

    Shield decouples user accounts from the data used to identify them through a concept called User Identities.

    • User Account: The central entity representing a person.
    • User Identity: A specific method of identification (e.g., email/password, access tokens, JWT).

    This decoupling allows a single user to have multiple ways to sign in (e.g., both a standard password and a third-party OAuth provider).

    Key Behaviors:

    • The email and password fields are automatically accessible from the User entity.
    • When calling $userModel->save($user), the email/password identity is automatically updated.
    • Important: If no email/password identity exists yet, you must pass both the email and password to the User instance before calling save().

    Caution: When querying users, ensure you pull in the email field to avoid N+1 query performance issues when displaying user information.

  9. Manage Access Token Scopes

    develop

    Scopes act as permissions granted to a token. Scopes are defined at the moment of token generation and cannot be changed later. A wildcard scope ['*'] grants access to all permissions.

    Once a user is authenticated via a token, use tokenCan() or tokenCant() to check permissions.

    // Generate a token with specific scopes
    $token = $user->generateAccessToken('Work Laptop', ['posts.manage', 'forums.manage']);
    
    // Check permissions after authentication
    if ($user->tokenCan('posts.manage')) {
        // Access granted
    }
    
    if ($user->tokenCant('forums.manage')) {
        // Access denied
    }
  10. Available Authenticators in Shield

    develop

    Shield provides four authentication methods to handle different web application and API scenarios. These are configured in Config\Auth using an associative array where the key is an alias and the value is the class name.

    By default, Shield uses the session authenticator. You can change the active authenticator by modifying the $defaultAuthenticator property in your configuration.

    // Config\Auth configuration structure
    public array $authenticators = [
        'session' => Session::class,
        'tokens'  => AccessTokens::class,
        'hmac'    => HmacSha256::class,
        // 'jwt'  => JWT::class,
    ];
    
    public string $defaultAuthenticator = 'session';
  11. Use wildcard permissions in the AuthGroups matrix

    develop

    In the Config\AuthGroups::$matrix property, you can use the * wildcard to grant permissions under a specific scope.

    • A wildcard matches exactly one full segment.
    • A trailing wildcard (e.g., admin.*) grants descendant permissions only.
    • Wildcards can appear between segments (e.g., forum.*.create).

    Important Rules:

    • The first segment cannot be *.
    • A standalone * does not grant all permissions.
    • Exact child permissions (e.g., forum.posts.create) do not grant the parent permission (forum.posts).
    • Use broad wildcards like admin.* carefully, as they grant access to any future child permissions added under that scope.
    public array $matrix = [
        'superadmin' => ['admin.*', 'users.*', 'beta.*'],
    ];
    
    // Example: 'forum.posts.*' matches 'forum.posts.create' and 'forum.posts.comments.delete'
    // but does NOT match 'forum.posts'.