Middleware & Security

Security Headers

The security_headers_middleware automatically injects a set of security headers into every response, in addition to the CSP header. It is activated via .with_header_security(true) in the builder.

Injected headers

HeaderValueProtection
Content-Security-PolicyDynamic (unique nonce per request)Restricts allowed sources for scripts, styles, images, etc.
X-Content-Type-OptionsnosniffPrevents the browser from guessing the MIME type — blocks MIME sniffing attacks
X-Frame-OptionsDENYPrevents embedding the page in an iframe — protects against clickjacking
X-XSS-Protection1; mode=blockEnables the XSS filter in legacy browsers (older IE/Edge)
Referrer-Policystrict-origin-when-cross-originSends full referrer on same-origin, origin only on cross-origin, nothing on HTTP→HTTPS
Permissions-Policygeolocation=(), microphone=(), camera=()Disables access to geolocation, microphone and camera
Cross-Origin-Embedder-Policyrequire-corpRequires cross-origin resources to be explicitly opted in (CORP)
Cross-Origin-Opener-Policysame-originIsolates the browsing context — prevents cross-origin attacks via window.opener
Cross-Origin-Resource-Policysame-originPrevents resources from being loaded by other origins
Strict-Transport-Securitymax-age=31536000; includeSubDomainsEnforces HTTPS for 1 year, subdomains included (HSTS)

Activation

CSP only (without additional security headers)

.middleware(|m| {
    m.with_csp(|c| c)
})

CSP + all security headers

.middleware(|m| {
    m.with_csp(|c| {
        c.with_header_security(true)
         .with_nonce(true)
    })
})

Full strict preset

.middleware(|m| {
    m.with_csp(|c| {
        c.policy(SecurityPolicy::strict())
         .with_header_security(true)
    })
})

Notes

HSTS (Strict-Transport-Security) — This header is always sent, even if the application runs on HTTP behind a reverse proxy. Browsers only honor it over HTTPS connections. In production, ensure your proxy (nginx, Caddy, Cloudflare…) terminates TLS.

COEP (Cross-Origin-Embedder-Policy: require-corp) — Required to use SharedArrayBuffer and certain high-performance APIs. It may block loading of cross-origin resources (images, scripts, fonts) that do not return the Cross-Origin-Resource-Policy header. If you load resources from third-party CDNs, verify their compatibility or disable COEP via a custom SecurityPolicy.

X-XSS-Protection — Legacy header, ignored by modern browsers (Chrome, Firefox). Kept for compatibility with older browsers.