在Rest API中使用HTTPBearerAuth时,Yii2 AccessControl提供Forbidden 403

时间:2015-10-26 05:27:03

标签: php rest yii2 yii2-validation

我正在使用HTTPBearerAuth

在我的基本控制器上进行身份验证
public function behaviors()
{
    $behaviors['authenticator'] = [
        'class' => CompositeAuth::className(),
        'authMethods' => [
            HttpBearerAuth::className(),
        ],
    ];

    return $behaviors;
}

在我的UserController扩展基本控制器上,并使用AccessControl允许访客用户访问登录。

public function behaviors()
{
    $behaviors = parent::behaviors();

    $behaviors['access'] = [
        'class' => AccessControl::className(),
        'only' => ['login', 'logout', 'signup'],
        'rules' => [
            [
                'actions' => ['login'],
                'allow' => true,
                'roles' => ['?'],
            ],
            [
                'actions' => ['logout'],
                'allow' => true,
                'roles' => ['@'],
            ],
        ],
    ];

    $behaviors['verbs'] = [
        'class' => VerbFilter::className(),
        'actions' => [
            'logout' => ['post'],
        ],
    ];

    return $behaviors;
}

当我尝试访问没有身份验证详细信息的登录时,我得到了

{
  "name": "Unauthorized",
  "message": "You are requesting with an invalid credential.",
  "code": 0,
  "status": 401,
  "type": "yii\web\UnauthorizedHttpException"
}

未经授权401.有了身份验证详细信息,我

{
  "name": "Forbidden",
  "message": "You are not allowed to perform this action.",
  "code": 0,
  "status": 403,
  "type": "yii\web\ForbiddenHttpException"
}

为什么我会这样做?

1 个答案:

答案 0 :(得分:0)

您可以使用onlyexcept取出AccessControl并在子行为中使用HTTPBearerAuth。

public function behaviors()
{
    $behaviors = parent::behaviors();
    //authentication only applies to actionIndex in child controller
    $behaviors['authenticator']['only'][] = 'index';

    return $behaviors;
}