Yii2: Can I apply authenticator behavior only to certain actions?

I always got "You are requesting with invalid credentials." but I need to have a public endpoint specifically designed for viewing, so that everyone can access the access token for access, and the rest of the actions with checking the token

This is part of my Api controller:

/** * @inheritdoc */ public function behaviors() { return [ 'contentNegotiator' => [ 'class' => ContentNegotiator::className(), 'formats' => [ 'application/json' => Response::FORMAT_JSON, //'application/xml' => Response::FORMAT_XML, ], ], 'verbFilter' => [ 'class' => VerbFilter::className(), 'actions' => $this->verbs(), ], 'access' => [ 'class' => AccessControl::className(), 'only' => ['view'], 'rules' => [ [ 'actions' => ['view'], 'allow' => true, 'roles' => ['?'], ], ], ], 'authenticator' => [ 'class' => CompositeAuth::className(), 'authMethods' => [ HttpBasicAuth::className(), HttpBearerAuth::className(), QueryParamAuth::className(), ], ], 'rateLimiter' => [ 'class' => RateLimiter::className(), ], ]; } 

I am trying to use:

 'access' => [ 'class' => AccessControl::className(), 'only' => ['view'], 'rules' => [ [ 'actions' => ['view'], 'allow' => true, 'roles' => ['?'], ], ], 

],

But authenticator behavior does not allow my view action to be a public action

+7
rest api php yii2
source share
2 answers

I found that solutions simply use the "only" or "exception" key in the authenticator behavior

 'authenticator' => [ 'class' => CompositeAuth::className(), 'except' => ['view'], 'authMethods' => [ HttpBasicAuth::className(), HttpBearerAuth::className(), QueryParamAuth::className(), ], ], 

Source: https://github.com/yiisoft/yii2/issues/4575 https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-filters.md#using-filters-

Thanks, enjoy Yii2 and REST;)

+15
source share

There are two properties of authenticator bypass by action 1. only => bypass the rest of the action in array 2. except => bypass configured only in the array

 public function behaviors() { $behaviors = parent::behaviors(); $behaviors['authenticator'] = [ 'class' => CompositeAuth::className(), 'except' => ['login', 'register','regenerate'], //'only'=>['index'], 'authMethods' => [ [ 'class' => HttpBasicAuth::className(), 'auth' => function ($username, $password) { $user = User::findByLogin($username); return $user->validatePassword($password) ? $user : null; } ], HttpBearerAuth::className(), QueryParamAuth::className() ], ]; return $behaviors; } 
0
source share

All Articles