Web application security · 5 MIN READ
CSRF: reject cross-origin writes with Sec-Fetch-Site and http.CrossOriginProtection
Protect cookie-authenticated endpoints with net/http's CrossOriginProtection, know what SameSite cookies add and recognize when a synchronizer token is still required.
Cross-site request forgery abuses ambient credentials. A page on another site submits a form or calls fetch toward your service, the browser attaches your session cookie, and your handler sees an authenticated request it never meant to accept. Since Go 1.25 the standard library ships http.CrossOriginProtection, which rejects non-safe cross-origin browser requests using the Sec-Fetch-Site and Origin headers instead of a per-form secret. This lesson shows what that check decides, where SameSite fits and what stays your responsibility.
security · A MAP OF THE IDEA
- Allow safe methods
- Read Sec-Fetch-Site
- Fall back to Origin
- Apply exemptions
Useful when
- No per-session token state and no changes to forms are required.
- One wrapper protects every route, including routes added later.
Watch out
- GET, HEAD and OPTIONS always pass, so they must never change state.
- Requests without Sec-Fetch-Site and Origin are allowed as non-browser clients.
Implementation & operation cost: One wrapper at startup; the ongoing cost is keeping GET handlers free of side effects and reviewing every bypass pattern.
The browser attaches the cookie; the server must ask who initiated
A forged request is genuine HTTP from the victim's own browser, with the victim's cookie and network address, so authentication succeeds. What differs is the initiator: a document from another origin started it. Modern browsers say so. Sec-Fetch-Site carries same-origin, same-site, cross-site or none (the user typed the URL or opened a bookmark), and the Origin header names the initiating origin on POST and CORS requests. Page scripts cannot set either header. A server that refuses state-changing requests initiated by another origin removes the attack without storing anything per session. Credentials that are not ambient, such as a bearer token the client adds to an Authorization header, are never attached by the browser on its own, so they are not exposed to CSRF in the first place.
Wrap the mux and probe it with every kind of client
The program wraps a ServeMux with http.NewCrossOriginProtection, trusts one partner origin, exempts a single-sign-on endpoint that receives a cross-site form post by design and replaces the default 403 body. Each probe sets the headers a particular client would send. httptest.NewRequest uses example.com as the Host, which is what the Origin fallback compares against.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
func newHandler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /transfer", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "transfer accepted")
})
mux.HandleFunc("GET /balance", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "balance shown")
})
mux.HandleFunc("POST /sso/acs", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "assertion checked")
})
cop := http.NewCrossOriginProtection()
if err := cop.AddTrustedOrigin("https://checkout.partner.example"); err != nil {
panic(err)
}
// The identity provider posts a signed form cross-site by design.
cop.AddInsecureBypassPattern("POST /sso/acs")
cop.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "cross-origin request rejected", http.StatusForbidden)
}))
return cop.Handler(mux)
}
type probe struct {
label, method, path, fetchSite, origin string
}
func main() {
h := newHandler()
probes := []probe{
{"same-origin form", "POST", "/transfer", "same-origin", "https://example.com"},
{"cross-site form", "POST", "/transfer", "cross-site", "https://attacker.example"},
{"sibling subdomain", "POST", "/transfer", "same-site", "https://blog.example.com"},
{"cross-site GET", "GET", "/balance", "cross-site", ""},
{"old browser, Origin only", "POST", "/transfer", "", "https://attacker.example"},
{"old browser, same host", "POST", "/transfer", "", "https://example.com"},
{"curl, no headers", "POST", "/transfer", "", ""},
{"trusted partner", "POST", "/transfer", "cross-site", "https://checkout.partner.example"},
{"SSO bypass pattern", "POST", "/sso/acs", "cross-site", "https://idp.example"},
}
for _, p := range probes {
req := httptest.NewRequest(p.method, p.path, nil) // Host is example.com
if p.fetchSite != "" {
req.Header.Set("Sec-Fetch-Site", p.fetchSite)
}
if p.origin != "" {
req.Header.Set("Origin", p.origin)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Printf("%-26s %d %s\n", p.label, rec.Code, strings.TrimSpace(rec.Body.String()))
}
}GET, HEAD and OPTIONS pass unconditionally, which is why the cross-site GET succeeds: handlers behind those methods must never change state. A POST with Sec-Fetch-Site: same-origin passes, and so would none; cross-site and same-site are both rejected, because a sibling subdomain is a different origin even though cookies treat it as the same site. Without Sec-Fetch-Site the check compares the Origin host with the Host header, and a request with neither header is treated as a non-browser client such as curl and passes. AddTrustedOrigin matches the full scheme://host[:port] string exactly. AddInsecureBypassPattern uses ServeMux pattern syntax, and a bypassed handler must authenticate the request another way; here the identity provider's signed assertion does that.
SameSite cookies narrow exposure; they do not make the decision
SameSite=Lax tells the browser to omit the cookie on cross-site subrequests and cross-site POST navigations while still sending it on top-level GET navigations, so a user following a link arrives logged in. Strict withholds it on those navigations too. Both are worth setting on a session cookie, as the session lesson does, but neither replaces an origin check. Site is not origin: blog.example.com and app.example.com are the same site, so a compromised or user-generated subdomain still gets your cookies attached to its requests. Browsers also disagree about the default when SameSite is omitted, and Lax still sends the cookie on top-level GETs, which leaves any state-changing GET handler exposed. Use SameSite to shrink the attack surface and CrossOriginProtection to make the decision.
Put the check outside everything else
Wrap the outermost handler so a route added next quarter is protected automatically, and keep exemptions to a short, reviewed list. Because a *gin.Engine implements http.Handler, cop.Handler(router) protects every Gin route without Gin-specific middleware. If a reverse proxy rewrites the Host header, the Origin fallback for older browsers compares against the wrong host; preserve Host at the proxy or register the public origin with AddTrustedOrigin. Review CORS separately: it decides which origins may read responses, a different question from which may send writes, and a credentialed CORS policy that reflects any origin leaks GET responses even while writes are blocked.
cop := http.NewCrossOriginProtection()
if err := cop.AddTrustedOrigin("https://admin.example.com"); err != nil {
log.Fatal(err)
}
// A *gin.Engine is an http.Handler, so one wrapper covers every route.
srv := &http.Server{
Addr: ":8080",
Handler: cop.Handler(router),
ReadHeaderTimeout: 5 * time.Second,
}This fragment runs in your own environment. AddTrustedOrigin returns an error for a value with a path, query or fragment, or without a scheme or host, so check it at startup. Call SetDenyHandler if clients expect a JSON error body; otherwise rejections get a plain-text 403. For a decision inside one handler, Check(r) returns the same error without writing a response.
When a synchronizer token is still needed
Header-based protection depends on the browser. CrossOriginProtection allows requests that carry neither Sec-Fetch-Site nor Origin, which covers API clients but also very old browsers that send neither on a form post. For a browser that sends Origin but not Sec-Fetch-Site it compares hosts only, so an http:// page on your own host looks like the https:// one; HSTS closes that gap. If policy requires protection for such clients, or if a state change must stay reachable through GET, add a synchronizer token: a random value bound to the session, embedded in each form and compared on submission. Tokens, usually together with re-authentication, also suit especially sensitive actions such as changing an account's email address. No CSRF defense survives XSS on your own origin, because injected script runs same-origin; that is the job of escaping and CSP.
Test the decision table
Test the protection as a table, as the program does: each kind of client, each method, trusted and untrusted origins, and every bypass pattern, asserting both the status and that the handler had no side effect. Review every GET handler for writes, because safe methods always pass. In an end-to-end browser test, submit a form from a second origin and expect a 403. Log rejections with method, path and Origin, so a legitimate integration broken by the check is visible within minutes instead of being reported as a vague 403 days later.
TAKE THIS WITH YOU
Wrap the whole handler in http.CrossOriginProtection, keep GET handlers free of side effects, set SameSite on session cookies as a second layer and add synchronizer tokens only where policy requires old-browser coverage.
Check your understanding
CrossOriginProtection receives a POST from blog.example.com to app.example.com with Sec-Fetch-Site: same-site. What happens?
Go to the source
Progress stays in this browser. No account needed.