Yii2:我可以仅针对某些操作应用身份验证器行为吗?

gsa*_*edo 9 php api rest yii2

我总是得到"你要求的证书无效." 但我需要有一个公共端点专门"查看"操作,每个人都可以访问whitout发送访问令牌并保持其他操作与令牌验证

这是我的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(),
        ],
    ];
}
Run Code Online (Sandbox Code Playgroud)

我尝试使用:

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

]

但验证者行为不允许我的视图操作是公共操作

gsa*_*edo 17

我发现解决方案只是在验证器行为上使用"only"或"except"键

'authenticator' => [
            'class' => CompositeAuth::className(),
            'except' => ['view'],
            'authMethods' => [
                HttpBasicAuth::className(),
                HttpBearerAuth::className(),
                QueryParamAuth::className(),
            ],
        ],
Run Code Online (Sandbox Code Playgroud)

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

谢谢,享受Yii2和REST;)