CHtml::linkButton and CSRF

Hi all.

I have CSRF check enabled.

And I got this error:

Bad Request

The CSRF token could not be verified.

The solution was add this param to linkButton method:

‘YII_CSRF_TOKEN’ => Yii::app()->request->csrfToken

All work ok now.

But, shouldn’t this be added automactly by Chtml::linkButton() ???

<?php echo CHtml::linkButton('Comprar', array('submit' => '',


                                              'params' => array('command'=>'comprar',


                                              'codigo'=>$produto->codigo,


                                              'YII_CSRF_TOKEN' => Yii::app()->request->csrfToken


                                        ),


                              'class'  => 'link-1',


                        ));


?>

Nice finding and solution.

Unfortunately, we could generate this automatically because a link button can target at different locations. And also in case when the button is enclosed by a form, a CSRF token is generated by the form.

For these reasons, I added a 'csrf' option to $htmlOptions. By setting this to true, it should achieve the same effect as you did.

Your explanation make sense and add csrf in options was a good solution!

Thumb up!

What’s about simple CHtml::ajaxLink method. It causes CSRF validation exception even if ‘csfr’ is set to ‘true’;

I think, we need to add some logic in public static function CHtml::ajax($options), to add CSRF data.

I am finding same issue with CHtml::ajaxSubmitButton

e.g.


 echo CHtml::ajaxSubmitButton('text', array('user/update', array('UserName'=>$data->UserName)), $ajaxOptions, array('csrf'=>true));


CHtml::ajaxLink('delete', 'delete/'.$data->id, array('type'=>'POST', 'data'=>array('YII_CSRF_TOKEN' => Yii::app()->request->csrfToken)));