我总是得到#34;您要求的凭证无效。"但我需要专门有一个公共端点" view"每个人都可以访问的操作发送访问令牌并使用令牌验证保留其他操作
这是我的Api控制器的一部分:
/**
* @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(),
],
];
}
我尝试使用:
'access' => [
'class' => AccessControl::className(),
'only' => ['view'],
'rules' => [
[
'actions' => ['view'],
'allow' => true,
'roles' => ['?'],
],
],
],
但验证者行为不允许我的视图操作是公共操作
答案 0 :(得分:16)
我发现解决方案仅仅是使用'或者'除了'验证者行为的关键
'authenticator' => [
'class' => CompositeAuth::className(),
'except' => ['view'],
'authMethods' => [
HttpBasicAuth::className(),
HttpBearerAuth::className(),
QueryParamAuth::className(),
],
],
来源: https://github.com/yiisoft/yii2/issues/4575 https://github.com/yiisoft/yii2/blob/master/docs/guide/structure-filters.md#using-filters-
谢谢,享受Yii2和REST;)
答案 1 :(得分:0)
有两个属性可绕过操作上的身份验证器 1. only =>绕过配置的阵列中的其余操作 2.除了=>绕过仅在数组中配置
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;
}