Enabling cookies in REST controllers

Original Post on Stack Overflow.

I have a headless application written in yii, with an Angular application using the yii2 api. Currently I’m using local storage for tokens, but I read this link and would like to store the token in a cookie.

Auth action:


\Yii::$app->response->cookies->add(new Cookie([

    'name' => 'token',

    'value'=> $token->__toString()

]));

AuthMethod:


if (($cookie = $cookies->get('token')) !== null) {

    die('Token found in cookie');

    $token = $parser->parse($cookie->value);

}

Using the native PHP $_COOKIE the cookie can be read by the yii2 application, but the setcookie() does not work. It looks like the yii2-rest controller strips away the headers before sending the response.

The token is always null, so it seems like cookies are disabled by default in Rest controllers / JSON responses, how can I enable this?

It is quite normal to disable cookies, etc. - check your REST application configuration.

I would use Angular to store / handle the cookies, because REST is (and should be) stateless.

Its still stateless when using a JWT token, its just safer storage in cookies.

I have not set any rest-specific config settings other than url rules. And I’ve tried turning sessions back on in the user-config (‘enableSession’ => true). Do you know if cookies are disabled by default in rest controllers?

EDIT:

for clarity, I’m testing all endpoints in POSTman and I have a backend HTML-based application as well (working with regular sessions and cookies out-of-the-box).

I am not using cookies (yet), but I have this in my config:


    	'request'          	=> [

        	'parsers' => [

            	'application/json' => 'yii\web\JsonParser',

        	],

        	'enableCookieValidation' => false,

        	'enableCsrfValidation'   => false,

    	],



I’ve played around with the config settings you’ve posted, but no luck.

The controller in question extends \yii\web\Controller, but uses Response::FORMAT_JSON.

The following code will return the cookie inside debug, but the cookie is still not sent in the request headers (Again, in POSTman).




\Yii::$app->response->cookies->add(new Cookie([

    'name' => 'token',

    'value'=> $token->__toString()

]));

$response->data['debug'] = \Yii::$app->response->cookies;



Any other ideas?