Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 set active user in API

Tags:

yii2

In Yii 1, I had this code in an API controller to set the active user:

Yii::$app->user->id = $my_userid;

But in Yii2, this is not allow, as Yii::$app->user->id is now read-only.

What would be the equivalent command to set active user id?

like image 884
lilbiscuit Avatar asked Oct 14 '25 09:10

lilbiscuit


1 Answers

You need to use setIdentity() method for API:

use Yii;

...

Yii::$app->user->setIdentity($user)

setIdentity(): changes the user identity without touching session or cookie. This is best used in stateless RESTful API implementation.

where $user should be valid instance of your User model.

If you need to change existing user, use switchIdentity() method instead:

use Yii;

...

Yii::$app->user->switchIdentity($user)
like image 177
arogachev Avatar answered Oct 17 '25 00:10

arogachev