首次提交:姜十三论坛
后端 Go+Gin:认证/CSRF/限流、板块、帖子、评论、点赞、通知、用户资料、置顶推荐;前端 Next.js 16:发帖/编辑/删除、搜索、分页、点赞、通知中心、设置;基础设施 docker-compose 与配置模板;添加 .gitignore 与专有许可证(保留所有权利)
This commit is contained in:
43
backend/middleware/security.go
Normal file
43
backend/middleware/security.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// SecurityHeaders 安全响应头中间件
|
||||
// 为所有响应添加安全头,降低 XSS、点击劫持、MIME 嗅探等风险
|
||||
func SecurityHeaders() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// CSP:限制资源加载来源,降低 XSS 危害
|
||||
c.Header("Content-Security-Policy",
|
||||
"default-src 'self'; "+
|
||||
"script-src 'self' 'unsafe-inline'; "+
|
||||
"style-src 'self' 'unsafe-inline'; "+
|
||||
"img-src 'self' data: https:; "+
|
||||
"font-src 'self' data:; "+
|
||||
"connect-src 'self'; "+
|
||||
"frame-ancestors 'none'; "+
|
||||
"base-uri 'self'; "+
|
||||
"form-action 'self'")
|
||||
|
||||
// HSTS:强制 HTTPS(生产环境生效,dev 模式浏览器会忽略)
|
||||
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
|
||||
|
||||
// 点击劫持防护
|
||||
c.Header("X-Frame-Options", "DENY")
|
||||
|
||||
// MIME 嗅探防护
|
||||
c.Header("X-Content-Type-Options", "nosniff")
|
||||
|
||||
// 控制 Referer 信息泄露
|
||||
c.Header("Referrer-Policy", "strict-origin-when-cross-origin")
|
||||
|
||||
// XSS 防护(旧浏览器兼容,现代浏览器靠 CSP)
|
||||
c.Header("X-XSS-Protection", "1; mode=block")
|
||||
|
||||
// 禁止浏览器缓存敏感页面(可按需覆盖)
|
||||
// c.Header("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user