PHPackages                             ddruganov/yii2-api-auth - 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. ddruganov/yii2-api-auth

ActiveYii2-extension

ddruganov/yii2-api-auth
=======================

Authentication tools for yii2

1.4.0(4y ago)043PHP

Since Feb 4Pushed 4y ago1 watchersCompare

[ Source](https://github.com/ddruganov/yii2-api-auth)[ Packagist](https://packagist.org/packages/ddruganov/yii2-api-auth)[ RSS](/packages/ddruganov-yii2-api-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (27)Used By (0)

yii2-api-auth
=============

[](#yii2-api-auth)

JWT auth server with rbac

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

[](#installation)

`composer require ddruganov/yii2-api-auth`

How-to
------

[](#how-to)

1. Add this to your app's main config:

```
...
    'components' => [
        AuthComponentInterface::class => AuthComponent::class,
        RbacComponentInterface::class => RbacComponent::class,
        AccessTokenProviderInterface::class => HeaderAccessTokenProvider::class
    ],
    'controllerMap' => [
        'auth' => AuthController::class,
        'app' => AppController::class,
        'permission' => PermissionController::class,
        'role' => PermissionController::class,
        'user' => PermissionController::class
    ],
...
```

2. Add this to your app's params:

```
...
    'authentication' => [
        'masterPassword' => [
            'enabled' => false,
            'value' => ''
        ],
        'tokens' => [
            'secret' => '',
            'access' => [
                'ttl' => 0, // seconds
                'issuer' => ''
            ],
            'refresh' => [
                'ttl' => 0 // seconds
            ]
        ],
        'maxActiveSessions' => 3
    ]
...
```

3. Add migrations in you console config for rbac features:

```
...
    'controllerMap' => [
        'migrate' => [
            'class' => MigrateController::class,
            'migrationPath' => null,
            'migrationNamespaces' => [
                'console\migrations',
                'ddruganov\Yii2ApiAuth\migrations',
            ],
        ],
    ],
...
```

Auth
----

[](#auth)

All methods require the `authenticate` permission;

- `POST auth/login` with email and password to login into the default app and get a pair of tokens
- `POST auth/login-into` with an app id when already authenticated to get authenticated in another app
- `POST auth/refresh` with your refresh token to get a fresh pair of tokens
- `POST auth/logout` to logout
- `GET auth/current-user` to get current user info
- `GET auth/verify` reserved; used by `ddruganov\yii2-api-auth-proxy`
- `POST auth/check-permission` reserved; used by `ddruganov\yii2-api-auth-proxy`
- Use `Yii::$app->get(AuthComponentInterface::class)->getCurrentUser()` to get the currently logged in `ddruganov\Yii2ApiEssentials\auth\models\User`
- Attach `AuthFilter` as a behavior to your `ApiController` to only allow authenticated users to access the endpoints
- Attach `RbacFilter` as a behavior to your `ApiController` to only allow users with specific permissions to access the endpoints

Obviously, your `User` class is gonna have more than just simple fields like `email` and `name` so you'll have to return a different user type from the `AuthComponent`. Easiest way:

```
final class YourAuthComponent extends Yii2ApiAuthComponent
{
    public function getCurrentUser(): ?YourUser
    {
        return YourUser::findOne($this->getPayloadValue('uid'));
    }
}
```

`YourUser` has to extend `ddruganov\Yii2ApiEssentials\auth\models\User`

Apps
----

[](#apps)

- `GET app/all` to get a list of all available apps
- `GET app/one` with an app uuid to get info about a single app
- `POST app/create` to create an app; requires the `app.create` permission
- `POST app/update` to update an app; requires the `app.update` permission
- `POST app/delete` to delete an app; requires the `app.delete` permission
- Use `Yii::$app->get(AuthComponentInterface::class)->login($user, $app)` to get a pair of tokens for the said app
- Do not forget to create permissions for newly created apps

Be ware that you cannot create a default app, only change the existing one to fit your data

Permissions
-----------

[](#permissions)

- `GET permission/all` to get a list of all available permissions; requires the `permission.view` permission
- `GET permission/one` with a permission id to get full info about a permission; requires the `permission.view` permission
- `POST permission/create` to create a permission; requires the `permission.create` permission
- `POST permission/update` to update a permission; requires the `permission.update` permission
- `POST permission/delete` to delete a permission (also deletes role bindings); requires the `permission.delete` permission

Roles
-----

[](#roles)

- `GET role/all` to get a list of all available roles; requires the `role.view` permission
- `GET role/one` with a role id to get full info about a role; requires the `role.view` permission
- `POST role/create` to create a role; requires the `role.create` permission
- `POST role/update` to update a role; requires the `role.update` permission
- `POST role/delete` to delete a role (also deletes permission and user bindings); requires the `role.delete` permission

Users
-----

[](#users)

- `GET user/all` to get a list of all available users; requires the `user.view` permission
- `GET user/one` with a user id to get full info about a user; requires the `user.view` permission
- `POST user/create` to create a user; requires the `user.create` permission
- `POST user/update` to update a user; requires the `user.update` permission
- `POST user/delete` to delete a user (also deletes role bindings); requires the `user.delete` permission

#### Example of extending user controller, forms and collectors:

[](#example-of-extending-user-controller-forms-and-collectors)

```
final class YourUpdateForm extends UpdateForm {
    public ?bool $isBanned = false;

    public function rules() {
        return ArrayHelper::merge(parent::rules(), [
            [['isBanned'], 'required']
        ]);
    }

    protected function setCustomAttributes(Model $model) {
        parent::setCustomAttributes($model);
        $model->setAttributes([
            'is_banned' => $this->isBanned
        ]);
    }
}
```

```
final class YourUserAllCollector extends UserAllCollector {
    protected function _run(): ExecutionResult {
        $query = YourUser::find()
            ->newestFirst()
            ->limit($this->limit)
            ->page($this->page);

        return ExecutionResult::success([
            'totalPageCount' => (clone $query)->getPageCount(),
            'users' => array_map(
                fn (User $user) => [
                    'id' => $user->getId(),
                    'email' => $user->getEmail(),
                    'name' => $user->getName(),
                    'isBanned' => $user->isBanned(),
                    'createdAt' => $user->getCreatedAt(),
                ],
                (clone $query)->all()
            )
        ]);
    }
}
```

```
final class YourUserController extends UserController {
    public function actions() {
        return ArrayHelper::merge(parent::actions(),[
            'all' => YourAllUserCollector::class,
            'update' => YourUpdateForm::class
        ]);
    }
}
```

`YourUser` has to extend `ddruganov\Yii2ApiEssentials\auth\models\User`

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity59

Maturing project, gaining track record

 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

Every ~3 days

Total

26

Last Release

1477d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b68509a8d66d630b4f6a4faef3a5cb2cbea6b5c78321cc6940aa78554a95a27a?d=identicon)[ddruganov](/maintainers/ddruganov)

---

Top Contributors

[![ddruganov](https://avatars.githubusercontent.com/u/12191677?v=4)](https://github.com/ddruganov "ddruganov (46 commits)")

###  Code Quality

TestsCodeception

### Embed Badge

![Health badge](/badges/ddruganov-yii2-api-auth/health.svg)

```
[![Health](https://phpackages.com/badges/ddruganov-yii2-api-auth/health.svg)](https://phpackages.com/packages/ddruganov-yii2-api-auth)
```

###  Alternatives

[kakadu-dev/yii2-jwt-auth

Extension provide JWT auth for Yii2

105.8k](/packages/kakadu-dev-yii2-jwt-auth)

PHPackages © 2026

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