yii2中的Rest身份验证(HttpBearerAuth)的覆盖响应

我有基于令牌的授权,为此我做了以下更改。

用户模型中,如下重写findIdentityByaccessToken()方法。

public static function findIdentityByaccessToken($token,$type = null)
{
  $userlogin = Userdevices::find()->where(['access_token' => $token])->one();

  if ($userlogin == array()) {
      return null;
  } else {
      $User = Users::findOne(['id' => $userlogin->user_id]);
      if (!count($User))
      {
          return null;
      }
      else {
          $dbUser = [
              'id' => $User->id,];
          return new static($dbUser);
      }
  }
}

在Controller中,我如下添加behaviors()

public function behaviors()
{
    $behaviors[] = [
        'class' => \yii\filters\ContentNegotiator::classname(),'formats' => [
            'application/json' => \yii\web\Response::FORMAT_JSON,],];

    $behaviors['authenticator'] = [
        'class' => HttpBearerauth::classname(),];

    return $behaviors;
}

当API无法获取令牌或令牌无效时,会给出以下响应

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

我要按照以下要求更改响应。

{
    "code": 401,"name": "Unauthorized","is_logout": "Y","status": "error","message": "logout"
}
coalawang 回答:yii2中的Rest身份验证(HttpBearerAuth)的覆盖响应

您可以使用beforeSend的{​​{1}}事件来更改响应的格式。

例如,在api控制器中添加以下方法:

yii\web\Response

控制器的public function init() { parent::init(); \Yii::$app->response->on( \yii\web\Response::EVENT_BEFORE_SEND,[$this,'beforeResponseSend'] ); } public function beforeResponseSend(\yii\base\Event $event) { /** * @var \yii\web\Response $response */ $response = $event->sender; if ($response->data['status'] == 401) { $response->data = [ 'code' => 401,'name' => 'Unauthorized','is_logout' => 'Y','status' => 'error','message' => 'logout',]; } } 方法注册init事件。 beforeSend方法处理事件并更改响应格式。

如果要在多个控制器中格式化响应,最好将事件处理程序放入自己的类中

beforeResponseSend

并在namespace app\components; class ErrorResponseHelper { public static function beforeResponseSend(Event $event) { // ... formating code ... } }

中注册事件
config/web.php

但是请谨慎使用此解决方案,因为这样return [ // ... 'components' => [ 'response' => [ 'class' => 'yii\web\Response','on beforeSend' => [ \app\components\ErrorResponseHelper::class,'beforeResponseSend',],]; 将在每次请求期间被调用。

本文链接:https://www.f2er.com/3166741.html

大家都在问