如何在 django 中添加 x-xss-protection 标头?

nff*_*lva 2 django header http

我似乎无法将 x-xss-protection 标头添加到 HttpResponse 对象。

基本上,我希望能够覆盖 x-xss-protection: "1; mode=block;" 标头,因为它在 Webkit 浏览器(Safari 和 Chrome)上给了我这个错误消息:

XSS 审计器拒绝执行 'http://...' 中的脚本,因为在请求中找到了它的源代码。由于服务器既未发送“X-XSS-Protection”也未发送“Content-Security-Policy”标头,因此启用了审核员

当我尝试在 HttpResponse 对象中添加 X-XSS-Protection http 标头时,我得到了这个:

得到了意外的关键字参数“x-xss-protection”

好像不支持x-xss-protection?!我可能做错了。

我不确定是否应该在应用程序级别 (django) 或 Web 服务器级别 (Apache/nginX) 添加它。

就我而言,最好直接在视图上执行,因为我不希望此漏洞在其他 django 视图上“未被发现”。

有什么建议吗?

小智 5

@mehmet 适合添加一些信息:

## X-XSS-Protection
SECURE_BROWSER_XSS_FILTER = True
Run Code Online (Sandbox Code Playgroud)

您还可以添加更安全的标头:更多信息:https : //docs.djangoproject.com/en/2.1/topics/security/

## X-Frame-Options
X_FRAME_OPTIONS = 'DENY'
#X-Content-Type-Options
SECURE_CONTENT_TYPE_NOSNIFF = True
## Strict-Transport-Security
SECURE_HSTS_SECONDS = 15768000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True

## that requests over HTTP are redirected to HTTPS. aslo can config in webserver
SECURE_SSL_REDIRECT = True 

# for more security
CSRF_COOKIE_SECURE = True
CSRF_USE_SESSIONS = True
CSRF_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SAMESITE = 'Strict'
Run Code Online (Sandbox Code Playgroud)


Meh*_*nce 4

django-secure 可以为你做到这一点。您可以通过 pip 安装它。

要在浏览器中启用 XSS 过滤器,并强制其始终阻止可疑的 XSS 攻击,可以通过 X-XSS-Protection: 1; 模式=块头。SECURE_BROWSER_XSS_FILTER如果设置为,SecurityMiddleware 将为所有响应执行此操作True

http://django-secure.readthedocs.org/en/latest/middleware.html