Encrypt REST Response Stream with Yii 2.0

I want to encrypt the REST-Request response stream. I take data from db and return it as xml (actionAll). It works great. Then I added an eventHandler that runs before the response is sent to the client (beforeAction). This also works. My problem is that the $ response in the encryptResponse method does not contain any data when the eventHandler calls it. The contents of variables, data, and stream are always null in the response object.

Thanks for any help!

<?php

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);
    }   
}
+4
source share
1 answer

You can set the response event in init.

return true beforeAction, null, , Yii2 .

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
}
+2

Source: https://habr.com/ru/post/1584484/


All Articles