这如何防止 csrf 攻击?

how does this protect against csrf attacks?

我正在制作我的 opencart 项目并使用 This Article 编写自定义 API。

它使用此代码块对 csrf 攻击进行安全检查:

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

我的问题是,根据文章,这将如何防止 csrf 攻击?似乎它只是将 Access-Control-Allow-Origin header 设置为请求来自的任何域

这根本不能防止 CSRF 攻击,因为您允许所有来源!和

一样的写法
Access-Control-Allow-Origin: *

您应该创建一个如下所示的接受列表,以确保只有列表中的接受列表才能获得 CORS。

Scheme, Domain and Port are the important information to compare against. Port can be omitted, when defaults are to be used like http=80 and https=443.

if(in_array($this->request->server['HTTP_ORIGIN'], [
    'http://xxx-domain.org',
    'https://example.org',
    'http://localhost:8888',
])) {
    $this->response->addHeader("Access-Control-Allow-Origin: {$this->request->server['HTTP_ORIGIN']}");
    $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    $this->response->addHeader('Access-Control-Max-Age: 1000');
    $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}