Yii2 - Handling user access token on frontend app

1k Views Asked by At

I am working in a project where an API (non OAuth) returns a token and expiration date if user access info is correct.

I have an application created using Basic Template Application.

Right now after I get the token I do:

...code to get token

Yii::$app->session->set('isGuest', false);
Yii::$app->session->set('user', $response->data->profile);

With This information I can check if user is logged in and give it access to certain areas of the site. The bad side is that I lost the possibility to use access rules in the controllers:

'rules' => [
                    [
                        'actions' => ['index', 'view', 'delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],

Is there a way I can make Yii think we have logged in and be able to use all methods as usual?

I guess I can use Webuser, but not sure the proper way to do it.

1

There are 1 best solutions below

0
On

You need to set the user's identity.

To successfully do this you should create a class that extends yii\filters\auth\AuthMethod that has a public function authenticate($user, $request, $response) {} (doc).

I created an implementation for JWT tokens, and my authenticate function will (after verifying the token) have the following lines:

$user_id = $token->getClaim('uid');
$identity = $user->login(User::findIdentity($user_id));

return $identity;

Then you can do something like this (my class is called JWTBearerAuth) in your controllers

/**
 * @inheritdoc
 */
public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => JWTBearerAuth::className(),
    ];
    return $behaviors;
}

And all your authorization code will work.