Skip to content
Advertisement

Turning YII_CSRF_TOKEN secure flag on

I have enabled CSRF Validation in Yii:

'enableCsrfValidation' => true,

Everything works as expected however I’d like for the session cookie to have the secure flag turned on.

With other cookies you can set the secure flag in the config:

'session'=>array(
    'cookieParams' => array(
        'httponly'=>true,
        'secure' => true,
    ),
),

How do you do this for the YII_CSRF_TOKEN?

Advertisement

Answer

You can’t do that with the built in CHttpRequest component. You will need to derive from it and override the createCsrfCookie() to create a secure cookie as follows:

class CustomHttpRequest extends CHttpRequest {

    protected function createCsrfCookie()
    {
        $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
        $cookie->secure = true; //Here is where you make your cookie secure
        if(is_array($this->csrfCookie))
        {
            foreach($this->csrfCookie as $name=>$value)
                $cookie->$name=$value;
        }
        return $cookie;
    }

}

In your components configuration, specify your custom implementation:

'components'=>array(
        ....,
        'request' => array(
            'class' => 'CustomHttpRequest',
            'enableCsrfValidation' => true,
        ),

IMPORTANT: For a new CSRF token to be generated, you will need to start a new browser session. Also, you will need to use HTTPS for a secure cookie to be in effect.

Delete all cookies for your development URI, or start a private session (in Chrome or Firefox) to start a new session.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement