4spacesdk/ci4authextension

与 CodeIgniter 4 简单集成的 OAuth2

v1.1.0 2024-09-28 13:31 UTC

README

安装

步骤 1)

composer require 4spacesdk/ci4authextension

步骤 2)

创建新文件 app/Config/AuthExtension.php 并添加以下内容

<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class AuthExtension extends BaseConfig {

    /*
     * Specify the database group
     */
    public string $dbGroupName = 'default';

    /*
     * If true, AuthExtension will extend routes with default endpoints
     * Check CI4AuthExtension/Hooks/PreController.php for details
     */
    public bool $autoRoute = true;

    /*
     * OAuth Access token lifetime in seconds
     */
    public int $oauthAccessTokenLifeTime = 15 * MINUTE;

    /*
     * OAuth Access token lifetime in seconds
     */
    public int $oauthRefreshTokenLifeTime = 7 * DAY;

    /*
     * Path to login page
     */
    public string $loginPage = '/login';

}

步骤 3)

将此行添加到您的 application/Config/Events.php 文件中

Events::on('pre_system', [\AuthExtension\Hooks\PreController::class, 'execute']);
Events::on('pre_command', [\AuthExtension\Hooks\PreController::class, 'execute']);

步骤 4)

添加迁移文件,并在 up() 中添加此行: \AuthExtension\Migration\Setup::migrateUp();,并在 down() 中添加此行: \AuthExtension\Migration\Setup::migrateDown();

步骤 5)

播种新用户,例如

$user = new User();
$user->first_name = 'Firstname';
$user->last_name = 'Lastname';
$user->username = 'some@email.com';
$user->password = password_hash('secret password', PASSWORD_BCRYPT);
$user->save();

步骤 6)

添加控制器和视图以进行简单的用户名/密码登录。您可以使用自己的登录检查算法或使用 $loginResponse = AuthExtension::login($username, $password);,这将返回这些常量之一,并在会话存储中设置 user_id

class LoginResponse {
    const Success           = 'Success';
    const RenewPassword     = 'RenewPassword';
    const WrongPassword     = 'WrongPassword';
    const UnknownUser       = 'UnknownUser';
}

通过会话授权

$user = AuthExtension::checkSession();
$userFALSE 或授权的用户。

通过 OAuth2 授权

如果您在 Config 中启用了 autoRoute,则可以通过调用 /check 并将 access_token 作为查询参数或头信息来授权。
查看 AuthExtension\Hooks\PreController 获取更多路由。