How get user data with Yii2 bearer authentication?

Multi tool use
How get user data with Yii2 bearer authentication?
I need to get the user data to use for the access control. I bearer authentication works fine, the user session is disabled.
public static function findIdentityByAccessToken ($token, $type = null) {
$user = static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
if ( $user ) {
if ( $user->isAccessTokenValid() ) {
$user->last_request = time();
$user->save(false);
return $user;
}
}
return null;
}
The Yii::$app->user->id
and Yii::$app->user->getId()
return null
because the session is disabled.
Yii::$app->user->id
Yii::$app->user->getId()
null
I need to use it in:
$behaviors['access'] = ['class' => AccessControl::class,
'only' => ['view'],
'rules' => [
[
'actions' => ['view'],
'allow' => false,
'roles' => User::isUserAdmin(Yii::$app->user->getId()),
],
[
'actions' => ['view'],
'allow' => true,
'roles' => User::isUserManager(Yii::$app->user->getId()),
],
],
];
I tried to save the user data or the token in public static variable in the user class, but the variable always null
.
null
Yii::$app->user->id
findIdentityByAccessToken
if ( $user->isAccessTokenValid() ) {
user
Yii::$app->user->id
also you need to specify the user
identityClass
in your components
configuration, make sure it is correct– Muhammad Omer Aslam
Jul 2 at 13:20
identityClass
components
It also depends on what returns the method
getId()
implemented inside your User class. If the class extends ActiveRecord then it should return it from db. Usually you'll find the loaded user under Yii::$app->user->identity
if identityClass is set up as suggested by @MuhammadOmerAslam. here is a working example in case you need anyone.– Salem Ouerdani
Jul 2 at 13:24
getId()
Yii::$app->user->identity
When I enable the session I can get the user id from
Yii::$app->user->id
, and the findIdentityByAccessToken
is returning true, also the 'identityCalss' is set.– Marvix
Jul 3 at 5:29
Yii::$app->user->id
findIdentityByAccessToken
The
getId' simply reading the user id from
$identity', and the problem the `$identity' is not been set.– Marvix
Jul 3 at 6:00
getId' simply reading the user id from
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
although the session is disabled but the
Yii::$app->user->id
will be populated for the current request and not across requests can you confirm that yourfindIdentityByAccessToken
method is not returning afterif ( $user->isAccessTokenValid() ) {
means does this statement returns true ? as it returns theuser
model object and if it does theYii::$app->user->id
should not be blank– Muhammad Omer Aslam
Jul 2 at 13:13