php - 这如何防止 csrf 攻击?
问题描述
我正在制作我的 opencart 项目并使用本文 编写自定义 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 标头设置为请求来自的任何域
解决方案
这根本不能防止 CSRF 攻击,因为您允许所有来源!和写法一样
Access-Control-Allow-Origin: *
您应该创建一个如下所示的接受列表,以确保只有列表中的那些被授予 CORS。
Scheme
,Domain
并且Port
是要比较的重要信息。当要使用默认值(如 http=80 和 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');
}
推荐阅读
- python - pandas bar plots x 轴的行为与直接校准 Axes.bar 不同
- laravel - 如何在laravel中将选定的下拉列表文本插入数据库
- list - 如何从飞镖/颤振列表中删除特定对象?
- r - 在 R 中生成随机排列
- file - 解密文件类型和内容
- bash - 在控制台上从一种语言翻译成英语
- linux - 节日音频播放
- c++ - Clang 问题 -Wunused-value 取决于是否从宏调用代码
- http - 如何使用 Rust/Axum 设计测试友好的应用程序?
- flutter - Flutter FutureBuilder 快照返回“对象”的实例而不是数据