Web application security · 5 MIN READ
Security headers: a per-request CSP nonce, HSTS, nosniff, frame-ancestors and Referrer-Policy
Write middleware that sets a nonce-based Content-Security-Policy and the other baseline security headers, and roll them out without breaking pages or locking in HSTS preload by accident.
Response headers turn browser features into policy: which scripts may run, whether the page may be framed, whether a response may be reinterpreted as another content type, how much of the URL leaks to other sites and whether plain HTTP is ever acceptable again. None of them fixes a bug in your handlers. They limit what an escaping mistake, an injected script or a hostile frame can do, so they belong in one middleware that wraps every response.
security · A MAP OF THE IDEA
- Generate nonce
- Set headers first
- Tag trusted scripts
- Report, then enforce
Useful when
- Injected scripts without the nonce do not run even if escaping fails.
- One middleware gives every response the same baseline policy.
Watch out
- HSTS includeSubDomains and preload are hard to undo; raise them deliberately.
- Cached HTML that contains a nonce shares that nonce across visitors.
Implementation & operation cost: 16 random bytes and a few header writes per response, plus the one-time work of moving inline handlers into nonce-tagged scripts.
What each header defends against
Content-Security-Policy restricts where scripts, styles, frames and other resources may come from; with a strict script-src an injected <script> tag does not run. Strict-Transport-Security tells the browser to use HTTPS for this host for max-age seconds, so a network attacker cannot downgrade a later visit. X-Content-Type-Options: nosniff stops browsers from deciding that a text/plain or image response is really HTML or script. The frame-ancestors directive of CSP controls which origins may embed the page, which defeats clickjacking; X-Frame-Options: DENY is the legacy equivalent for old browsers, and a browser that enforces frame-ancestors ignores it when both are sent. Referrer-Policy limits how much of the current URL is sent in the Referer header. Leave out X-XSS-Protection: the filter it controlled is gone from modern browsers and could itself be abused.
Headers middleware with a per-request nonce
The middleware draws a 128-bit nonce from crypto/rand for every response, sets all headers before calling the next handler and stores the nonce in the request context. The handler renders it into the one script tag it trusts. To show what CSP adds, a bug elsewhere has marked a stored comment as template.HTML, so an injected script tag reaches the page. Two requests go through httptest, and the program prints the first response with the random nonce masked.
package main
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"html/template"
"net/http"
"net/http/httptest"
"strings"
)
type nonceKey struct{}
func newNonce() string {
b := make([]byte, 16)
rand.Read(b) // never returns an error; crashes the program if the OS source fails
return base64.RawURLEncoding.EncodeToString(b)
}
// securityHeaders sets the policy before the inner handler writes anything.
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nonce := newNonce()
h := w.Header()
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'nonce-"+nonce+"'; "+
"object-src 'none'; base-uri 'none'; frame-ancestors 'none'")
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), nonceKey{}, nonce)))
})
}
var page = template.Must(template.New("page").Parse(
`<script nonce="{{.Nonce}}">start()</script><p>{{.Comment}}</p>`))
func handler(w http.ResponseWriter, r *http.Request) {
nonce, _ := r.Context().Value(nonceKey{}).(string)
var buf bytes.Buffer
err := page.Execute(&buf, map[string]any{
"Nonce": nonce,
// A bug elsewhere marked stored user input as trusted HTML.
"Comment": template.HTML(`<script>steal()</script>`),
})
if err != nil {
http.Error(w, "render failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
buf.WriteTo(w)
}
func nonceFrom(csp string) string {
_, rest, _ := strings.Cut(csp, "'nonce-")
nonce, _, _ := strings.Cut(rest, "'")
return nonce
}
func main() {
h := securityHeaders(http.HandlerFunc(handler))
var nonces []string
for range 2 {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "https://example.com/", nil))
nonce := nonceFrom(rec.Header().Get("Content-Security-Policy"))
if len(nonces) == 0 {
for _, name := range []string{"Content-Security-Policy", "Strict-Transport-Security",
"X-Content-Type-Options", "X-Frame-Options", "Referrer-Policy"} {
fmt.Printf("%s: %s\n", name, strings.Replace(rec.Header().Get(name), nonce, "<nonce>", 1))
}
fmt.Println("body:", strings.Replace(rec.Body.String(), nonce, "<nonce>", 1))
}
nonces = append(nonces, nonce)
}
fmt.Println("nonce length:", len(nonces[0]))
fmt.Println("fresh nonce per response:", nonces[0] != nonces[1])
}script-src lists only the nonce, so a browser runs the script tag that carries it and refuses the injected one, which has no nonce and could not have guessed it; that is defense in depth on top of the escaping lesson, not a replacement. default-src 'self' covers other resource types, object-src 'none' disables plugins and base-uri 'none' stops an injected <base> tag from redirecting relative script URLs. The handler renders into a buffer first, so a template error becomes a clean 500 instead of half a page. The 16 random bytes become 22 base64url characters, which need no escaping inside an HTML attribute, and the second response gets a different value. Headers are set before next runs because header changes after WriteHeader are ignored.
CSP in practice: nonces, caching and a report-only rollout
A nonce works only if an attacker cannot predict or reuse it, so generate one per response, never per process or per user, and do not let a CDN cache HTML that contains it, or every visitor shares one value. Static pages cannot carry a fresh nonce; allow their inline scripts by hash ('sha256-...') instead. Under this policy inline event handlers such as onclick and javascript: URLs are blocked, so move that code into nonce-tagged scripts. Introduce a new policy as Content-Security-Policy-Report-Only with a report-to or report-uri endpoint, read the violations for a release or two, then enforce it. Keep the policy string in one place in code, so a page that needs an exception gets a reviewed, narrow change instead of 'unsafe-inline'.
HSTS: start short, preload last
Browsers ignore Strict-Transport-Security on plain-HTTP responses, so sending it on every response is harmless; it takes effect after the first HTTPS visit. Start with a short max-age such as 300 seconds, raise it to a year once every page and API works over HTTPS, and add includeSubDomains only when every subdomain, including internal tools and forgotten marketing hosts, serves valid HTTPS. The preload directive asks browser vendors to ship your domain in a built-in HTTPS-only list. Removal takes months to reach users, and meanwhile any subdomain without a working certificate is unreachable for everyone, so preload is a deliberate, owner-approved step, never a default in shared middleware. If TLS terminates at a load balancer, set HSTS there or here, but in exactly one place.
The same middleware in Gin
In Gin the policy is a middleware registered with r.Use before any route. c.Header sets a response header, c.Set stores the nonce for handlers and c.HTML renders through html/template, which escapes the nonce attribute like any other value. Register it on the engine rather than on a route group so that 404 and recovery responses carry the headers too, then assert them in a router test.
func SecurityHeaders() gin.HandlerFunc {
return func(c *gin.Context) {
nonce := newNonce()
c.Set("cspNonce", nonce)
c.Header("Content-Security-Policy", "default-src 'self'; script-src 'nonce-"+nonce+"'; "+
"object-src 'none'; base-uri 'none'; frame-ancestors 'none'")
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("X-Frame-Options", "DENY")
c.Header("Referrer-Policy", "strict-origin-when-cross-origin")
c.Next()
}
}
// In a handler:
// c.HTML(http.StatusOK, "page.tmpl", gin.H{"Nonce": c.GetString("cspNonce")})This fragment runs in your own Gin service and reuses newNonce from the program. c.Next runs the rest of the chain after the headers are set, so a handler can still override one header for one route, which is where a reviewed exception belongs. Gin builds its 404 chain from the engine's global middleware, so unmatched routes get these headers as well.
Test and review the headers
Test headers as the program does: send requests through the full handler chain with httptest and compare each header with an exact expected string, masking only the nonce. Include an error page, a redirect, a static file and a 404, since those responses most often bypass middleware. Check that two responses never share a nonce and that the nonce in the header equals the one in the page. For pages whose URLs carry secrets, such as password-reset links, send Referrer-Policy: no-referrer on that response. In review, treat any new 'unsafe-inline', 'unsafe-eval', wildcard source or HSTS preload as a security change that needs its own justification.
TAKE THIS WITH YOU
Set CSP with a fresh per-response nonce, nosniff, frame-ancestors plus X-Frame-Options, Referrer-Policy and a gradually raised HSTS in one outer middleware, and treat preload as a separate, deliberate decision.
Check your understanding
Why must the CSP script nonce change on every response instead of being fixed per deployment?
Go to the source
Progress stays in this browser. No account needed.