我正在构建一个自定义 Joomla 组件,并将其添加到我的模板 (default.php) 文件中的表单中(它使用的是 HTTP POST):
echo JHTML::_( 'form.token' ); //add hidden token field to prevent CSRF vulnerability
然后我检查我的控制器中的令牌:
JRequest::checkToken() or die( 'Invalid Token' );
但无论我做什么,我都会得到一个无效的令牌。当我在 html 页面上查看源代码时,我已经验证了在我的表单中创建了一个带有令牌的隐藏类型。我还验证了,在控制器中,token的值是一样的:
print_r(JUtility::getToken());
因此,如果令牌是相同的值,为什么它会以 Invalid Token 消息退出?
编辑:有一个我没有提到的关键部分。我的表单是在一个单独的 js 文件中使用 jquery ajax 处理的,该文件添加到我的 view.html.php 中。这是 ajax POST 的样子:
jQuery.ajax({
type: 'POST',
url: 'index.php?option=com_recordings&task=deletevideos&format=raw',
data: {checkedarray:checked},
success: function(data){
//delete row
}
});
控制器对此进行处理:
function deletevideos()
{
$video_list = JRequest::getVar('checkedarray', 0, 'post', 'array');
//print_r(JUtility::getToken());
JRequest::checkToken() or jexit( 'Invalid Token' );
$model = &$this->getModel();
return $model->setDeleteVideos($video_list);
}
This then goes to the model that does the DB update. I saw this old post that might be relevant. It is not clear to me how/where I generate the token and where/how I validate that token. The post seems quite involved as it checks against users as well which I don't think is needed in my case. Or maybe I misunderstand?
EDIT #2
Okay so the token is missing and I need to pass it into my js file. So I thought I could add this to my view.html.php:
$addtoken = JUtility::getToken();
$addtokenjs = 'jQuery(function() {
var token="'.$addtoken.'";
});';
$doc->addScriptDeclaration( $addtokenjs );
$doc->addScript(JURI::base()."components/com_recordings/js/recordings.js");
I have to put this in the document ready function because apparently addScriptDeclaration does not put anything ahead of my recordings.js file. Then pass the token into the ajax
call:
jQuery.ajax({
type: 'POST',
url: 'index.php?option=com_recordings&task=deletevideos&format=raw'+token+'=1',
data: {checkedarray:checked},
success: function(data){
//delete row
}
});
Apparently I'm not doing this right as I get this error: ReferenceError: token is not defined
.