lilbiscuit
lilbiscuit

Reputation: 2249

Yii2 set active user in API

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?

Upvotes: 4

Views: 2128

Answers (1)

arogachev
arogachev

Reputation: 33538

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)

Upvotes: 6

Related Questions