Yii2:我可以仅将验证器行为应用于某些操作吗


Yii2: Can I apply authenticator behavior just to some actions?

我总是得到"您使用无效凭据进行请求。"但我需要有一个公共端点,特别是"查看"操作,每个人都可以访问该操作,发送访问令牌,并使用令牌验证保留其他操作

这是我的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' => ['?'],
         ],
    ],

],

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

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

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

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

谢谢,享受Yii2和REST;)

有两个属性可以在操作中绕过验证器1.仅=>绕过配置的阵列中的其余操作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;
}