Files
jiang13-bbs/backend/middleware/security.go
freefire 0c2b0d2d6a 首次提交:姜十三论坛
后端 Go+Gin:认证/CSRF/限流、板块、帖子、评论、点赞、通知、用户资料、置顶推荐;前端 Next.js 16:发帖/编辑/删除、搜索、分页、点赞、通知中心、设置;基础设施 docker-compose 与配置模板;添加 .gitignore 与专有许可证(保留所有权利)
2026-09-12 01:11:05 +08:00

44 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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()
}
}