I have a REST API where user authentication is working as expected. I can access user identity with Yii::$app->user->identity.
User updated_at field is a critical information for frontend application, so I would like to attach it to every response. I’ve tried to create the following custom response:
<?php
namespace api\components;
use Yii;
class CustomResponse extends yii\web\Response
{
public function init()
{
parent::init();
$user=Yii::$app->user->identity;
$lastUpdate=$user->updated_at;
$this->headers->set('lastUpdate',$lastUpdate);
}
}
However, Yii::$app->user->identity returns null even after authenticating correctly on the controller that precedes the response.
According to the docs: “By default, yii\web\Response::send() method will be called automatically at the end of yii\base\Application::run().”. I’m assuming that Yii::$app->user->identity is lost at the end of application execution and before yii\web\Response::send().
I’ve tried to add the authentication behavior to the custom response component in the same way that it is added on controllers that need authentication:
<?php
namespace api\components;
use Yii;
class CustomResponse extends yii\web\Response
{
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['authenticator'] = [
'class' => 'api\components\CustomHttpBearerAuth',
];
return $behaviors;
}
public function init()
{
parent::init();
$user=Yii::$app->user->identity;
$lastUpdate=$user->updated_at;
$this->headers->set('lastUpdate',$lastUpdate);
}
}
The result is the same: Yii::$app->user->identity returns null;
How can I add user->updated_at to every response?