php yii 锁,php – 使用Yii 2.0加密REST响应流

我想加密REST-Request的响应流.我从数据库中获取数据并将其作为xml(actionAll)返回.这很好用.然后我添加了一个在响应发送到客户端之前执行的eventHandler(beforeAction).这也有效.我的问题是,当eventHandler调用它时,encryptResponse方法中的$response不包含任何数据.变量content,data和stream在response-object中始终为null.

谢谢你的帮助!

namespace app\controllers;

use Yii;

use app\models\Order;

use yii\filters\auth\HttpBasicAuth;

use yii\web\Response;

use app\models\User;

class OrderController extends \yii\rest\Controller{

/**

* disable session for REST-Request

* no loginUrl required

*/

public function init(){

parent::init();

\Yii::$app->user->enableSession = false;

\Yii::$app->user->loginUrl = null;

}

/**

* HttpBasicAuth for authentication

*/

public function behaviors(){

$behaviors = parent::behaviors();

$behaviors['authenticator'] = [

'class' => HttpBasicAuth::className(),

'auth' => function ($username, $password) {

if($username==\Yii::$app->params['HttpBasicAuth']['username'] && $password==\Yii::$app->params['HttpBasicAuth']['password']){

return new User();

}else{

return null;

}

}];

return $behaviors;

}

/**

* set response-format to xml

* fetch data from db

*

*/

public function actionAll(){

\Yii::$app->response->format = \yii\web\Response::FORMAT_XML;

$models = Order::find()->all();

return $models;

}

/**

* hook into action and add event handler

*/

public function beforeAction($action){

$response = Yii::$app->getResponse();

$response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);

}

/**

* callback for event-handler

*/

public function encryptResponse(){

$response = Yii::$app->getResponse();

var_dump($response);

}

}

解决方法:

您可以在init中设置响应事件.

或者您只需要在beforeAction函数中添加return true,否则数据将为null,因为未调用该操作,这在Yii2 docs here中也有提及.

use Yii;

...

public function init()

{

parent::init();

Yii::$app->user->enableSession = false;

Yii::$app->user->loginUrl = null;

Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);

}

public function beforeAction($action)

{

$response = Yii::$app->getResponse();

$response->on(Response::EVENT_BEFORE_SEND, [$this, 'encryptResponse']);

return true; // << required

}

标签:php,rest,yii,yii2

来源: https://codeday.me/bug/20190702/1360468.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值