The Problem: Yii2 utilizes by default UserIdentity configured in config/web.php for connection, this object apply one table to authentication ('identityClass' => 'app\panel\models\User'). How to authentication from diferent tables? Solution: Create instances in web.php to uses UserIdentify. eg:
$user = \Yii::$app->user;
$school = \Yii::$app->school;
$teacher = \Yii::$app->teacher;
My config/web.php
'user' => [
'class'=>'yii\web\User',
'identityClass' => 'app\models\User',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['dashboard/login'],
'identityCookie' => [
'name' => '_panelUser',
]
],
'school'=>[
'class'=>'yii\web\User',
'identityClass' => 'app\models\SchoolUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['dashboard-school/login'],
'identityCookie' => [
'name' => '_panelSchool',
]
],
'teacher'=> [
'class'=>'yii\web\User',
'identityClass' => 'app\models\TeacherUser',
'enableAutoLogin' => false,
'authTimeout' => 60*30,
'loginUrl' => ['dashboard-teacher/login'],
'identityCookie' => [
'name' => '_panelTeacher',
]
],
Note that for each there is a identifyClass and one view login. Now, we need to create the models:
namespace app\models;
use Yii;
// My user
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public static function tableName()
{
return '{{%user}}';
}
// to continues....
Model school:
namespace app\models;
use Yii;
// My School
class SchoolUser' extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public static function tableName()
{
return '{{%schoolUser}}';
}
// to continues
Model Teacher:
namespace app\models;
use Yii;
// My School
class TeacherUser'' extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
public static function tableName()
{
return '{{%teacher}}';
}
// to continues....
Now In my example I want to have controllers for each type of access, without generating conflicts between them:
In Behavior of the controller i have defined for dashboard-school, teacher and user, the user object representing the authentication status or the ID of the user application component.
//behaviors of the school
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'user'=>'school', // this user object defined in web.php
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
[
'allow' => true,
'actions' => ['login'],
'roles' => ['?'],
],
],
]
];
}
To use login:
//school
\Yii::$app->scholl->login($model, $this->rememberMe ? 3600*24*30 : 0);
//teacher
\Yii::$app->teacher->login($model, $this->rememberMe ? 3600*24*30 : 0);
For restrict access in views:
<?php if (!\Yii::$app->scholl->isGuest):?>
<h1>My school Name: <?=\Yii::$app->scholl->identity->name?>
<?php endif;?>
<?php if (!\Yii::$app->teacher->isGuest):?>
<h1>Teacher Name: <?=\Yii::$app->teacher->identity->name?>
<?php endif;?>
Always use the specific instance of the user you want to work with.
Criticism, suggestions and improvements, use the comments
It's worked for me. how can i using the behaviors functions for different identifyClass.
I have my config file as follows:
'admin' => [
'class'=>'yii\web\User', 'identityClass' => 'app\models\Admin', 'enableSession' => true, ], 'employee' => [ 'class'=>'yii\web\User', 'identityClass' => 'app\models\Employee', 'enableSession' => true, ],It gives me error as follows:
User::identityClass must be set.
20444 so, "'identityClass' => 'app\models\User'" is required.
from it you can create other instances like the illustrated example.
I can not explain very well, but the core of yii requires a class User Identify for this.
Follow information:
https://www.yiiframework.com/doc/guide/2.0/en/security-authentication#implementing-identity
If you need to change identity model class in behaviors
//behaviors of the schoolpublic function behaviors()
{
return [ 'access' => [ 'class' => AccessControl::className(), 'user'=> \Yii::$app->school, // this school object defined in web.php 'rules' => [ [ 'allow' => true, 'roles' => ['@'], ], [ 'allow' => true, 'actions' => ['login'],'roles' => ['?'],
}
Hi Everyone,
How can we implement RBAC with such a case. I am using RBAC and I am following above step, but It is didn't work with RBAC.
Hi everyone, I have done all this stuff but it didn't work. When I logged-in with a type of user, it tried to use the id of my user for each user's type. I fixed this problem by changing the 'idParam' of each identityClass:
'school'=>[ 'class'=>'yii\web\User', 'identityClass' => 'app\models\SchoolUser', 'enableAutoLogin' => false, 'authTimeout' => 60*30, 'loginUrl' => ['dashboard-school/login'], 'identityCookie' => [ 'name' => '_panelSchool', ], 'idParam' => '_id_school' ], 'teacher'=> [ 'class'=>'yii\web\User', 'identityClass' => 'app\models\TeacherUser', 'enableAutoLogin' => false, 'authTimeout' => 60*30, 'loginUrl' => ['dashboard-teacher/login'], 'identityCookie' => [ 'name' => '_panelTeacher', ], 'idParam' => '_id_teacher' ],All this logic actually isn't working now. Once you redirect to home, when you check if your component is guest, it will return true. My advice is to go to https://www.yiiframework.com/wiki/2545/using-multiple-models-in-an-identity to achieve it.
Excellent article, using multiple yii\web\User components with distinct identityClass bindings is a solid way to support authentication across separate tables in Yii2. This pattern works especially well when each actor (User, SchoolUser, TeacherUser) implements IdentityInterface independently and has its own session + cookie scope.
From a technical standpoint, a few important additions that help make this production-safe:
Make sure each component defines a unique idParam and identityCookie name to avoid session overwrites between identities when multiple roles authenticate in the same browser.
If RBAC is enabled, ensure your authorization checks are bound to the correct component (Yii::$app->school->can() vs Yii::$app->user->can()), otherwise permissions will resolve against the default auth manager context.
When using AccessControl, explicitly set the user property to the intended component instance to prevent fallback to the default user component.
Verify that each identity model properly implements findIdentity(), getId(), and token validation logic — mismatches there often cause the “guest after redirect” issue people report.
Also consider separate session namespaces if you are mixing stateless APIs and session-based logins.
We’ve implemented similar multi-identity and multi-guard Yii2 architectures (including RBAC + multi-session isolation) in real-world systems — sharing some deeper implementation notes and patterns here: https://duewebstudio.com/
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.