-
Notifications
You must be signed in to change notification settings - Fork 10
/
secure.go
94 lines (79 loc) · 2.26 KB
/
secure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package middleware
import (
"fmt"
"github.com/twiglab/twig"
)
type (
// SecureConfig 安全中间件配置
SecureConfig struct {
Skipper Skipper
// XSSProtection 防御跨域攻击(XSS)
// 设置 `X-XSS-Protection`
// 可选,默认为 "1; mode=block".
XSSProtection string
// ContentTypeNosniff 设置`X-Content-Type-Options`
ContentTypeNosniff string
// XFrameOptions
// 可选,默认为"SAMEORIGIN".
// 可选的值为:
// - "SAMEORIGIN"
// - "DENY"
// - "ALLOW-FROM uri"
XFrameOptions string
// HSTSMaxAge 设置`Strict-Transport-Security`
// 可选,SSL链接下默认为31536000
HSTSMaxAge int
// HSTSExcludeSubdomains 排除子域名
// 可选,默认false
HSTSExcludeSubdomains bool
ContentSecurityPolicy string
}
)
var (
DefaultSecureConfig = SecureConfig{
Skipper: DefaultSkipper,
XSSProtection: "1; mode=block",
ContentTypeNosniff: "nosniff",
XFrameOptions: "SAMEORIGIN",
HSTSMaxAge: 31536000,
}
)
// Secure 返回Secure中间件
func Secure() twig.MiddlewareFunc {
return SecureWithConfig(DefaultSecureConfig)
}
// SecureWithConfig
func SecureWithConfig(config SecureConfig) twig.MiddlewareFunc {
if config.Skipper == nil {
config.Skipper = DefaultSecureConfig.Skipper
}
return func(next twig.HandlerFunc) twig.HandlerFunc {
return func(c twig.Ctx) error {
if config.Skipper(c) {
return next(c)
}
req := c.Req()
res := c.Resp()
if config.XSSProtection != "" {
res.Header().Set(twig.HeaderXXSSProtection, config.XSSProtection)
}
if config.ContentTypeNosniff != "" {
res.Header().Set(twig.HeaderXContentTypeOptions, config.ContentTypeNosniff)
}
if config.XFrameOptions != "" {
res.Header().Set(twig.HeaderXFrameOptions, config.XFrameOptions)
}
if (c.IsTls() || (req.Header.Get(twig.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge != 0 {
subdomains := ""
if !config.HSTSExcludeSubdomains {
subdomains = "; includeSubdomains"
}
res.Header().Set(twig.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains))
}
if config.ContentSecurityPolicy != "" {
res.Header().Set(twig.HeaderContentSecurityPolicy, config.ContentSecurityPolicy)
}
return next(c)
}
}
}