停止在Yii2中使用响应正文发送访问令牌

问题描述 投票:3回答:2

我正在使用Yii2开发一个rest API,前端是由ionic开发的。这种情况是,当我有一个它使用承载认证的动作时...它工作正常但访问令牌与响应主体一起返回,导致客户端的HttpErrorResponse:

  SyntaxError: Unexpected token y in JSON at position 0 at Json.parse

响应像这样返回,因此客户端无法解析json

 y2sSCEXqkUoVY2BjkQZqx8g3W42273Cz{"success":false,"message":"you liked it before"}

这是使用承载认证的行为代码

  public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['contentNegotiator'] = [
        'class' => ContentNegotiator::className(),
        'formats' => [
            'application/json' => Response::FORMAT_JSON,
        ],
    ];
    // remove authentication filter
    $auth = $behaviors['authenticator'];
    unset($behaviors['authenticator']);
    // add CORS filter
    $behaviors['corsFilter'] = [
        'class' => CorsCustom::className(),
    ];
    // re-add authentication filter
    $behaviors['authenticator'] = $auth;
    // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
    $behaviors['authenticator']['except'] = ['options'];
    $behaviors['authenticator'] = [
        'class' => CompositeAuth::className(),
        'only' => ['like', 'unlike', 'likes', 'create'],
        'authMethods' => [
            HttpBearerAuth::className(),
        ],
        ];

    return $behaviors;
}

我想停止在正文中发送访问令牌或将其作为json发送

rest authentication yii2 bearer-token
2个回答
3
投票

我认为你应该从你的USER模型中删除echo $token语句

public static function findIdentityByAccessToken($token, $type = null)
{
    /* echo $token; */
    return static::findOne(['auth_key' => $token]);
}

3
投票

在回复之前停止echo令牌,你将完成你的工作!

public static function findIdentityByAccessToken($token, $type = null)
{
    /* echo $token; */
    return static::findOne(['auth_key' => $token]);
}
© www.soinside.com 2019 - 2024. All rights reserved.