Security Headers
Add browser security headers to every response.
Security Headers
middleware.SecurityHeaders sets common browser security headers before the
handler runs.
app.Use(middleware.SecurityHeaders())The defaults set:
| Header | Value |
|---|---|
X-Content-Type-Options | nosniff |
X-Frame-Options | DENY |
Referrer-Policy | strict-origin-when-cross-origin |
Permissions-Policy | camera=(), microphone=(), geolocation=() |
HSTS is disabled by default. Content Security Policy and
Cross-Origin-Opener-Policy are also unset unless you provide them.
Custom options
app.Use(middleware.SecurityHeaders(middleware.SecurityHeadersOptions{
FrameOptions: "SAMEORIGIN",
ContentSecurityPolicy: "default-src 'self'; img-src 'self' data:",
CrossOriginOpenerPolicy: "same-origin",
HSTSMaxAge: 365 * 24 * time.Hour,
HSTSIncludeSubdomains: true,
HSTSPreload: true,
}))| Option | Description |
|---|---|
ContentSecurityPolicy | Full Content-Security-Policy value |
FrameOptions | DENY or SAMEORIGIN |
ReferrerPolicy | Referrer policy value |
PermissionsPolicy | Browser feature policy |
CrossOriginOpenerPolicy | same-origin, same-origin-allow-popups, or unsafe-none |
HSTSMaxAge | HSTS lifetime. Zero disables the header |
HSTSIncludeSubdomains | Adds includeSubDomains |
HSTSPreload | Adds preload |
HSTS
Only enable HSTS after the site works over HTTPS. Browsers cache the policy for the configured lifetime, so a mistake can lock users out of the HTTP version.
Start with a short lifetime and no preload during rollout:
HSTSMaxAge: 5 * time.Minute,Increase the lifetime after the HTTPS setup is stable. The preload directive
does not submit the domain to browser preload lists. That requires a separate
submission.
Content Security Policy
CSP can break inline scripts, styles, and third-party widgets. Build the policy from the assets the application actually loads, test it in report-only mode at the proxy, then enforce it here.
Ordering
Place security headers before handlers that may write a response:
app.Use(
middleware.RequestID(),
middleware.SecurityHeaders(),
middleware.Logger(),
)
Ply