我正在使用Phil Sturgeon的REST服务器,我想知道如何正确地进行CSRF保护?目前我正在使用这种方法:
if(stripos($_SERVER["REQUEST_URI"],'API')!=""){
$config['csrf_protection'] = FALSE;
}else{
$config['csrf_protection'] = TRUE;}
但是,我已经读过,这不是防止csrf攻击的正确方法。我试图扩展MY_Security,但我不确定在扩展课程后我需要做什么。这是扩展类
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Security extends CI_Security {
public function csrf_verify()
{
// If it's not a POST request we will set the CSRF cookie
if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST')
{
return $this->csrf_set_cookie();
}
/**
* mine implementation for application/json
*/
$reqHeaders = getallheaders();
$content_type = $reqHeaders["Content-Type"];
#it's a json request?
if(preg_match("/(application\/json)/i",$content_type))
{
#the check the cookie from request
$reqCookies = explode("; ",$reqHeaders["Cookie"]);
foreach($reqCookies as $c)
{
if(preg_match("/(".$this->_csrf_cookie_name."\=)/", $c))
{
$c = explode("=",$c);
if($_COOKIE[$this->_csrf_cookie_name] == $c[1])
{
return $this;
}
}
}
}
//< end
// Check if URI has been whitelisted from CSRF checks
if ($exclude_uris = config_item('csrf_exclude_uris'))
{
$uri = load_class('URI', 'core');
foreach ($exclude_uris as $excluded)
{
if (preg_match('#^'.$excluded.'$#i'.(UTF8_ENABLED ? 'u' : ''), $uri->uri_string()))
{
return $this;
}
}
}
// Do the tokens exist in both the _POST and _COOKIE arrays?
if ( ! isset($_POST[$this->_csrf_token_name], $_COOKIE[$this->_csrf_cookie_name])
OR $_POST[$this->_csrf_token_name] !== $_COOKIE[$this->_csrf_cookie_name]) // Do the tokens match?
{
$this->csrf_show_error();
}
// We kill this since we're done and we don't want to polute the _POST array
unset($_POST[$this->_csrf_token_name]);
// Regenerate on every submission?
if (config_item('csrf_regenerate'))
{
// Nothing should last forever
unset($_COOKIE[$this->_csrf_cookie_name]);
$this->_csrf_hash = NULL;
}
$this->_csrf_set_hash();
$this->csrf_set_cookie();
log_message('info', 'CSRF token verified');
return $this;
}
}
我是否需要为每个json POST设置标头或获取请求?这是我发送到REST后端的示例
public function user_create_activity($activity){
$this->curl->create(UserCreateActivity);
$this->curl->http_login(REST_KEY_ID,REST_KEY_PASSWORD);
$this->curl->post(array(
'activity' => $activity,
));
return json_decode($this->curl->execute(),true);
}
我不确定自己是否走在正确的道路上。希望有人可以指导我。
谢谢。