因此,我计划在我的网站中实现CSRF,并设置所需的内容,我认为我设置正确,但仍然存在ajax提交表单的问题。
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_token_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = FALSE;
$config['csrf_exclude_uris'] = array();
这就是我在配置中的内容,在配置中我设置了$config['CSRF_REGENERATE']=false;
以防止每次提交时的重新生成(基于此讨论Ajax CSRF 403禁止的codeigniter)。
而我的表单,我没有使用html表单标记,而是使用form_open()
和form_close()
。
Ajax提交表单:
$('#formData').on('submit', function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: 'post',
cache : false,
processData: false,
dataType: 'json',
url: 'example.com.sg/login/verify',
data: formData,
success: function (res) {
if(res.status == true){
window.location.href = res.redirect;
}
},
error: function(err){
console.log(err.responseText)
}
});
})
PHP函数
public function verify(){
$this->form_validation
->set_rules('email', 'Email', 'trim|required|valid_email')
->set_rules('password', 'Password', 'trim|required');
if($this->form_validation->run() == true){
// do email and password verification
echo json_encode([ 'status' => true, 'redirect' => base_url('dashboard') ]);
} else {
$this->returnFormError($this->form_validation->error_array());
}
}
如果我将ajax类型更改为get
,它可以工作,但不能工作post
。如果从控制台查看代码,我的表单在隐藏输入中包含此csrf令牌。
//在config.php中$config['encryption_key']='some key';首先更新这个