I’m building a REST API using Yii 2. For authentication, I’m using HttpBearerAuth class by attaching it to my controllers behaviors.
Some of my API actions must be available both for logged and guest users, and the controller logic may differ in each case (I would check Yii::$app->user->isGuest value inside the controller to run logged users specific code). The issue is: attaching HttpBearerAuth seems to makes it required to the user to be logged, instead I would receive a 401 response. This overrides Access Control Rules, when what I expected was to login the user if the Bearer token is passed & is valid, or simply not login if Bearer token is not passed.
So, how can I share a controller for both logged I guest users using HttpBearerAuth authenticator?
This is how my behaviors current’s is:
'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, //always allow for both logged and guest users! 'actions' => ['my-action-here'], ], ], ], 'authenticator' => [ 'class' => \yii\filters\auth\HttpBearerAuth::className(), //this makes rules useless! ],