Hello! I am using advanced template of Yii2 application. Created this common action:
<?php
namespace common\actions;
use yii\base\Action;
use Yii;
class ShareIdentityAction extends Action
{
public function run($outerSessId = '', $token = '')
{
// @@@ Put headers here
if ($token) return $this->loginWithToken($token);
else if ($outerSessId && Yii::$app->user->identity) return $this->requestToken($outerSessId);
return false;
}
// Suppose there are full-featured functions (I just cut a little).
protected function requestToken($outerSessId) return false;
protected function loginWithToken($token) return false;
}
It’s properly referenced in SignInControllers of both sites (frontend and backend) and whole code is working fine ― token is generated and can be used to login on other context (backend <-> frontend). And implementing AJAX POST cross-origin requests depends on these headers:
you should call Yii::$app->response->headers->set() to set header value which will overwrite an existing header, I find it weird why set is not working for you there is possibility these headers are overwritten, maybe remove other actions and test this action alone by itself
here is an example action I used to test it works fine with a newly create yii app
<?php
namespace app\actions;
use Yii;
class FooAction extends \yii\base\Action
{
public function run()
{
Yii::$app->response->headers->set('Pragma', 'cache');
return 'foo';
}
}
// sitecontroller which uses my FooAction
public function actions()
{
// ...
return [
'foo' => [
'class' => 'app\actions\FooAction'
]
];
// ...
}
That’s exact thing I do except there is no set but add. Unfortunately, both variants don’t work. Bump. Where I need put my headers? Are they sent before action run?
I am not sure what your code look likes but as you mentioned in your original post you have an action which you are using in both back-end as well front-end app, this should not by any different the example I gave you is also an action which I test with the basic app and it works. perhaps some other part of your code is overwriting the headers.
if you are trying to add CORS headers then you might as well use cors filter provided by Yii as @Arockia mentioned that will much better solution.