CSRF Protection Without Tokens in Fiber
Say a user leaves a form open over lunch, clicks Save and gets a 403 because
the token in the page has expired. Or an HTMX fragment is rendered without the
hx-headers attribute that carries the token, or a SPA keeps sending the token
it read at startup after the session rotated. None of these is an attack. They
are plumbing: every template, fetch wrapper and cached page has to carry a value
from the server back to the server, and one gap turns into a support ticket.
On HTTPS with current browsers, you can drop that plumbing. Every major browser
engine now sends the Sec-Fetch-Site header, which tells the server where a
request comes from and which script cannot forge.
csrf.NewCrossOriginProtection checks it together with Origin, sets no
cookie, needs no storage and puts nothing in your templates.
The one real risk in switching is a legitimate client you did not know about, such as a partner who embeds your form or an old in-house tool. Run the new check in report-only mode next to your tokens first, and its log shows who would be blocked before anyone is.
Go 1.25 added the same check to the standard library as
http.CrossOriginProtection, and Fiber
v3.6.0 brought it to
Fiber as
csrf.NewCrossOriginProtection
(#4596). It needs v3.6.0 or
later, which in turn requires Go 1.26, and I tested everything below against
Fiber v3.6.1.
Two Headers a Page Cannot Forgeβ
In a CSRF attack, a hidden form on evil.example posts to
https://notes.example.com/notes, the browser attaches the session cookie, and
your handler sees an authenticated request. A token stops it with a value that
page cannot read. The header check asks instead whether a page on your own
origin started the request.
Origin names the origin of the page that started the request, but browsers do
not send it on every request, and older ones were inconsistent about it.
Sec-Fetch-Site, one of the Fetch
Metadata
headers, states the relationship directly: same-origin for your own pages,
same-site for another subdomain of the same registrable domain, cross-site
for everything else, and none when the user typed the URL or opened a
bookmark.
Both are forbidden header names: script on the attacker's page cannot set or
change them, neither with fetch nor with a form. A non-browser client can send
anything, but it does not hold your user's cookies. According to
caniuse, Chromium-based
browsers sent Sec-Fetch-Site first, Firefox followed with version 90, and
Safari 16.4 closed the gap in March 2023. Browsers send Fetch Metadata only to
secure origins: HTTPS in production, localhost while you develop.
The middleware
documentation lists
the decision rules. GET, HEAD and OPTIONS always pass. Other methods pass
when Sec-Fetch-Site is same-origin or none, when the request carries
neither header, when an older browser sends only Origin and its host equals
the Host header, or when Origin is in TrustedOrigins. Everything else goes
to ErrorHandler with csrf.ErrCrossOriginRequest. A request without either
header passes on purpose: the check assumes it is same-origin or not a browser
at all, so curl scripts, mobile apps and webhook senders keep working without
configuration. A very old browser that sends no Origin on a form POST
passes the same way, even when the form sits on another site.
SameSite Cookies Trust Your Sibling Subdomainsβ
A session cookie with SameSite=Lax is often treated as CSRF protection on its
own, and against a random attacker site it mostly is. But "site" in SameSite
means the registrable domain. A form on blog.example.com posting to
notes.example.com is same-site and gets a Lax or even Strict cookie. If
the blog runs a vulnerable plugin, or a subdomain points at a cloud bucket
somebody else has claimed, that page can make authenticated requests to your
notes service.
The header check denies a same-site request unless its exact origin is in
TrustedOrigins, as does csrf.New, whose origin check also wants an exact
match. Coming from tokens, sibling subdomains stay blocked; coming from SameSite
cookies alone, they become blocked for the first time, which is the point.
What Changes When You Replace csrf.Newβ
If you replace csrf.New, these differences change behavior:
csrf.NewtreatsTRACEand the newQUERYmethod as safe. The tokenless check, likenet/http, exempts onlyGET,HEADandOPTIONS, so a frontend on another origin that calls yourQUERYendpoints needs to be inTrustedOrigins.OriginandTrustedOriginsare compared as sent. Configured entries are normalized for case and trailing slash, but default ports are not folded:https://dashboard.example.com:443in the config does not match theOrigin: https://dashboard.example.coma browser sends. Write origins without the default port, as browsers serialize them.csrf.Newfalls back to theRefererheader on HTTPS whenOriginis missing. The tokenless check never readsReferer.- A request that repeats
Sec-Fetch-Site, or repeatsOriginwhere the decision depends on it, is denied: with no single value to decide on, the check fails closed. - The default
ErrorHandlerreturnsfiber.ErrForbiddento your app's error handler. With Fiber's default one, a SPA receives the plain textForbidden, not your usual JSON error. SetErrorHandlerif your clients parse error bodies.
A Notes Service With Three Kinds of Clientsβ
The example renders a form on / and accepts it on POST /notes, serves
POST /api/notes to a dashboard at https://dashboard.example.com, and
receives the login result from an identity provider on POST /auth/callback.
This is its entire CSRF setup (the full main.go is at the end):
app.Use(cors.New(cors.Config{
AllowOrigins: []string{dashboardOrigin},
AllowCredentials: true,
}))
app.Use(csrf.NewCrossOriginProtection(csrf.CrossOriginConfig{
TrustedOrigins: []string{dashboardOrigin},
ErrorHandler: crossOriginDenied,
Next: func(c fiber.Ctx) bool {
if c.Method() != fiber.MethodPost {
return false
}
route := c.Endpoint()
return route != nil && route.Name == "oidc.callback"
},
}))
Compared with a token setup, the form has no hidden _csrf field, the CORS
config lists no X-Csrf-Token header, and there is no session store or
__Host- cookie for the token. All of that can go once the new check is
enforced.
curl sends neither header unless asked, so a plain call plays the server-to-server case:
curl -i -X POST -H 'Content-Type: application/json' \
-d '{"text":"from curl"}' http://localhost:3000/api/notes
HTTP/1.1 201 Created
...
{"id":1}
The attack is a hidden form on another site posting to /notes. Browsers send
it without a CORS preflight, because application/x-www-form-urlencoded,
multipart/form-data and text/plain bodies count as simple requests, which
is why a strict CORS config never stopped CSRF. The browser marks the request
cross-site:
curl -i -X POST -H 'Sec-Fetch-Site: cross-site' \
-H 'Origin: https://evil.example' -d 'text=pwned' \
http://localhost:3000/notes
HTTP/1.1 403 Forbidden
...
{"error":"cross-origin request blocked"}
The custom ErrorHandler, crossOriginDenied, logs both headers the decision
was based on:
2026/10/18 12:11:33 csrf: denied POST /notes (Sec-Fetch-Site="cross-site", Origin="https://evil.example"): csrf: cross-origin request denied
The dashboard sends Sec-Fetch-Site: same-site with its trusted origin and
gets a 201; the same request from https://blog.example.com gets the 403.
When a legitimate client is blocked in production, the log line shows which
header was missing or unexpected, which the default bare 403 does not.
Three Exceptions Most Apps Needβ
Few apps accept writes only from their own pages, and each of these exceptions takes a different fix.
The Dashboard Belongs in Two Listsβ
The dashboard calls the API with credentials from its own subdomain and needs
two entries: AllowOrigins in the CORS config, so the browser lets it send JSON
and read the response, and TrustedOrigins, so the cross-origin check lets the
write through. CORS controls what another origin may read, the cross-origin
check what it may change.
Forgetting the second list is the typical migration bug, and a dev server that
proxies API calls hides it: with a proxy setting in Vite or a similar tool, the
browser talks to localhost:5173 for page and API alike, every request is
same-origin, and the first 403 arrives in staging. Without such a proxy you
see it locally, since localhost:5173 and localhost:3000 are different
origins. Feed both lists from one constant, as the example does with
dashboardOrigin, or from one slice for several frontends.
Keep the list short: every origin in TrustedOrigins can make any change your
logged-in users can make. Wildcards such as https://*.example.com are accepted
and also trust the subdomain that serves user uploads and the forgotten
marketing microsite, so list exact origins. Entries must use http or https:
a value like capacitor://localhost makes the constructor panic at startup with
[CSRF] Invalid origin format in configuration:[redacted]. The redaction is
deliberate and cannot be turned off for this constructor, so find the bad entry
by hand.
The Login Callback Is Exempt by Route Nameβ
OpenID Connect with response_mode=form_post ends a login with an
auto-submitted form from the identity provider's origin to your callback, and
payment flows with 3-D Secure do the same. That POST is cross-site by design,
and TrustedOrigins alone cannot fix it: after a redirect chain across several
sites the browser may send Origin: null instead of the provider's origin, and
sandboxed iframes on any site send that too. The route has to be exempted.
The documentation example does that in Next by comparing c.Path(), which
works. The service ties the exemption to the route instead: the callback is
registered with .Name("oidc.callback"), and Next asks
c.Endpoint(), also added in v3.6.0, which route will
handle the request:
Next: func(c fiber.Ctx) bool {
if c.Method() != fiber.MethodPost {
return false
}
route := c.Endpoint()
return route != nil && route.Name == "oidc.callback"
},
If the callback moves to another path, the exemption moves with it, and spellings that reach the same handler are covered too, such as a trailing slash under the default non-strict routing:
curl -s -o /dev/null -w '%{http_code}\n' -X POST \
-H 'Sec-Fetch-Site: cross-site' -H 'Origin: https://id.example.org' \
-d 'state=abc&code=x' http://localhost:3000/auth/callback/
303
This has two costs. c.Endpoint() scans the remaining routes in the request's
tree bucket, a second router lookup. Next returns early for anything but
POST, yet every POST, including those to /api/notes, still pays for it.
If that matters, attach the middleware only to the routes that need it, here
everything under /api and POST /notes, and leave the callback out. And
route names are not unique in Fiber: a second route someone else names
oidc.callback is silently exempt as well, so treat the name like a security
setting and make it distinctive.
An exempted route has to protect itself. For OIDC that is the state
parameter, compared with the value you stored before redirecting to the
provider. The example only checks that it is present, which is not enough for
production.
Webhooks Pass Without an Exemptionβ
Stripe, GitHub and your own backend services send neither Sec-Fetch-Site nor
Origin, so they pass, and the middleware does nothing for those routes. Verify
webhook signatures as before.
A Report-Only Phase Next to the Tokensβ
ErrorHandler can turn the check into a report. It receives the request
context, and if it calls c.Next() instead of returning an error, the request
continues down the chain:
// reportOnly logs requests the check would block and lets them through.
func reportOnly(c fiber.Ctx, err error) error {
log.Printf("csrf report-only: would deny %s %s "+
"(Sec-Fetch-Site=%q, Origin=%q, User-Agent=%q): %v",
c.Method(), c.Path(),
c.Get(fiber.HeaderSecFetchSite), c.Get(fiber.HeaderOrigin),
c.Get(fiber.HeaderUserAgent), err)
return c.Next()
}
Set ErrorHandler: reportOnly and keep your existing csrf.New registered
after it, so the tokens still protect you while you watch. In a test with both
in that order, a cross-site POST produced the report line and was then
rejected by csrf.New, exactly as before the change. Calling c.Next() from
ErrorHandler is not a documented feature. It works because the error handler
runs inside the middleware with the same context, which I verified against the
v3.6.1 source, so check it again when you upgrade.
During the overlap, csrf.New needs the same exemption for the identity
provider callback through its own Next option, or logins break. The report
line also holds the user agent and origin of real users, which may count as
personal data depending on where your logs go, so set a retention period.
The report-only log has one blind spot. A request with neither Sec-Fetch-Site
nor Origin passes without ever reaching ErrorHandler, and that is exactly
the group that loses protection when the tokens go: very old browsers that send
no Origin on a form POST. Count them with a small middleware registered next
to the check:
// writesWithoutOrigin logs unsafe requests without Sec-Fetch-Site and Origin.
// The cross-origin check allows them without calling ErrorHandler.
func writesWithoutOrigin(c fiber.Ctx) error {
switch c.Method() {
case fiber.MethodGet, fiber.MethodHead, fiber.MethodOptions:
return c.Next()
}
site := c.Get(fiber.HeaderSecFetchSite)
if site == "" && c.Get(fiber.HeaderOrigin) == "" {
log.Printf("csrf audit: %s %s without Sec-Fetch-Site or Origin "+
"(User-Agent=%q)",
c.Method(), c.Path(), c.Get(fiber.HeaderUserAgent))
}
return c.Next()
}
This log also catches your curl scripts, mobile apps and webhook senders,
which never had a browser session to abuse. Entries with a browser user agent
are the ones that matter: those users depend on the tokens, and removing
csrf.New would leave their requests unchecked.
After a week of traffic, origins you recognize go into TrustedOrigins or an
exemption. Unknown ones are attacks, which the tokens still stop, or clients you
need to talk to. Once the report-only log is quiet and the audit log shows no
browsers, switch to the enforcing handler and run it next to the tokens for a
while.
An environment variable that selects the handler at startup makes switching
back a configuration change only while csrf.New and the token plumbing are in
place. Once they are gone, reportOnly lets every unsafe cross-origin request
through with no CSRF defense at all, and a rollback means redeploying the token
version. Keep that commit easy to find.
Eleven Requests That Define the Policyβ
A header-based check is easy to break with an innocent refactoring, such as
renaming a route. A table test against app.Test documents the policy and
catches that, one row per kind of client with the headers its browser would
send:
const note = `{"text":"a"}`
tests := []struct {
name string
path, body string
fetchSite string
origin string
wantStatus int
}{
{"curl or another server", "/api/notes", note,
"", "", 201},
{"own page", "/api/notes", note,
"same-origin", "https://notes.example.com", 201},
{"trusted dashboard", "/api/notes", note,
"same-site", "https://dashboard.example.com", 201},
{"sibling subdomain", "/api/notes", note,
"same-site", "https://blog.example.com", 403},
{"attacker form", "/notes", "text=a",
"cross-site", "https://evil.example", 403},
{"cross-site without Origin", "/notes", "text=a",
"cross-site", "", 403},
{"typed URL or bookmark", "/notes", "text=a",
"none", "", 303},
{"identity provider", "/auth/callback", "state=s&code=c",
"cross-site", "https://id.example.org", 303},
{"identity provider, trailing slash", "/auth/callback/",
"state=s&code=c", "cross-site", "null", 303},
{"old browser, same host", "/notes", "text=a",
"", "http://example.com", 303},
{"old browser, other host", "/notes", "text=a",
"", "http://evil.example", 403},
}
httptest.NewRequest sets the Host header to example.com, which the two
"old browser" rows rely on to exercise the fallback for browsers that send
Origin but no Sec-Fetch-Site. All eleven cases pass against v3.6.1. The
table covers only POST because the service has no other unsafe routes; if
yours has PUT, PATCH or DELETE handlers, add a cross-site row for each
method. When you add a frontend or an exempt route, add its row first and watch
it fail.
Where Tokens Still Winβ
The tokenless check is not a strict upgrade. In these cases I would keep
csrf.New, or think hard first.
Old browsers. A very old one that sends no Origin on a form POST passes
unchecked, like any non-browser client. For a consumer site that group is small.
If you serve kiosks, embedded devices or enterprise desktops that are years
behind, let the audit middleware count those requests first.
Plain HTTP. Browsers send no Fetch Metadata to a non-secure origin other than
localhost, so such a deployment depends on the Origin-versus-Host
comparison for every request. That comparison looks at hosts, not schemes: a
page on http://notes.example.com passes a check on
https://notes.example.com. On HTTPS, current browsers send Sec-Fetch-Site
and never get there, which leaves only old ones exposed, and HSTS closes that
hole, because a browser that has seen the header no longer talks to your host
over plain HTTP. The helmet
middleware sends Strict-Transport-Security only when
HSTSMaxAge is above zero, which is not the default, and only when
c.Secure() is true. Behind a TLS-terminating proxy, that requires TrustProxy
and a TrustProxyConfig that trusts the proxy, so Fiber believes its
X-Forwarded-Proto header. Setting the header at the proxy is often simpler.
Reverse proxies. The Origin-versus-Host comparison reads the Host header
exactly as it arrives and ignores X-Forwarded-Host, even with TrustProxy
enabled. If your proxy rewrites Host to the upstream address, old browsers are
denied on your own forms, while current browsers pass on
Sec-Fetch-Site: same-origin. Forward the original Host, which most proxy
setups do anyway, or add your public
origin to TrustedOrigins.
Some things no CSRF defense covers. State changes behind GET are never
checked, so a GET /notes/42/delete link is as dangerous as before. An XSS bug
on your own origin turns the attacker's script into a same-origin request, and
tokens do not help there either, since script on your page can read them.
An XSS bug on a trusted origin is where the two approaches part, and it weighs
more with every origin you trust. With csrf.New, a script on
dashboard.example.com still needs a valid token, and it can only get one if
your app hands it out to that origin, for example through a CORS-readable
endpoint that returns the token. With the tokenless check, the same script
passes. The origin match is the entire check.
The Complete Notes Serviceβ
main.go (108 lines)
package main
import (
"log"
"strings"
"sync"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/gofiber/fiber/v3/middleware/csrf"
)
// The dashboard is a separate SPA that calls the JSON API with credentials.
const dashboardOrigin = "https://dashboard.example.com"
type Note struct {
Text string `json:"text" form:"text"`
}
type store struct {
mu sync.Mutex
notes []Note
}
func (s *store) add(n Note) int {
s.mu.Lock()
defer s.mu.Unlock()
s.notes = append(s.notes, n)
return len(s.notes)
}
func crossOriginDenied(c fiber.Ctx, err error) error {
log.Printf("csrf: denied %s %s (Sec-Fetch-Site=%q, Origin=%q): %v",
c.Method(), c.Path(),
c.Get(fiber.HeaderSecFetchSite), c.Get(fiber.HeaderOrigin), err)
return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
"error": "cross-origin request blocked",
})
}
func newApp() *fiber.App {
app := fiber.New()
notes := &store{}
app.Use(cors.New(cors.Config{
AllowOrigins: []string{dashboardOrigin},
AllowCredentials: true,
}))
app.Use(csrf.NewCrossOriginProtection(csrf.CrossOriginConfig{
TrustedOrigins: []string{dashboardOrigin},
ErrorHandler: crossOriginDenied,
Next: func(c fiber.Ctx) bool {
if c.Method() != fiber.MethodPost {
return false
}
route := c.Endpoint()
return route != nil && route.Name == "oidc.callback"
},
}))
app.Get("/", func(c fiber.Ctx) error {
c.Type("html")
return c.SendString(`<form method="post" action="/notes">
<input name="text"> <button>Save</button>
</form>`)
})
app.Post("/notes", func(c fiber.Ctx) error {
var n Note
if err := c.Bind().Form(&n); err != nil {
return err
}
notes.add(n)
return c.Redirect().Status(fiber.StatusSeeOther).To("/")
})
app.Post("/api/notes", func(c fiber.Ctx) error {
var n Note
if err := c.Bind().JSON(&n); err != nil {
return err
}
if strings.TrimSpace(n.Text) == "" {
return fiber.NewError(fiber.StatusUnprocessableEntity,
"text is required")
}
id := notes.add(n)
return c.Status(fiber.StatusCreated).JSON(fiber.Map{"id": id})
})
// The identity provider posts the login result back from its own origin
// (OIDC response_mode=form_post), so this one route must accept it.
app.Post("/auth/callback", func(c fiber.Ctx) error {
if c.FormValue("state") == "" {
return fiber.ErrBadRequest
}
// Validate state and exchange the code here.
return c.Redirect().Status(fiber.StatusSeeOther).To("/")
}).Name("oidc.callback")
return app
}
func main() {
app := newApp()
if err := app.Listen(":3000"); err != nil {
log.Fatal(err)
}
}
main_test.go (72 lines)
package main
import (
"net/http/httptest"
"strings"
"testing"
"github.com/gofiber/fiber/v3"
)
func TestCrossOriginProtection(t *testing.T) {
app := newApp()
const note = `{"text":"a"}`
tests := []struct {
name string
path, body string
fetchSite string
origin string
wantStatus int
}{
{"curl or another server", "/api/notes", note,
"", "", 201},
{"own page", "/api/notes", note,
"same-origin", "https://notes.example.com", 201},
{"trusted dashboard", "/api/notes", note,
"same-site", "https://dashboard.example.com", 201},
{"sibling subdomain", "/api/notes", note,
"same-site", "https://blog.example.com", 403},
{"attacker form", "/notes", "text=a",
"cross-site", "https://evil.example", 403},
{"cross-site without Origin", "/notes", "text=a",
"cross-site", "", 403},
{"typed URL or bookmark", "/notes", "text=a",
"none", "", 303},
{"identity provider", "/auth/callback", "state=s&code=c",
"cross-site", "https://id.example.org", 303},
{"identity provider, trailing slash", "/auth/callback/",
"state=s&code=c", "cross-site", "null", 303},
{"old browser, same host", "/notes", "text=a",
"", "http://example.com", 303},
{"old browser, other host", "/notes", "text=a",
"", "http://evil.example", 403},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(fiber.MethodPost, tt.path,
strings.NewReader(tt.body))
contentType := fiber.MIMEApplicationForm
if tt.body == note {
contentType = fiber.MIMEApplicationJSON
}
req.Header.Set(fiber.HeaderContentType, contentType)
if tt.fetchSite != "" {
req.Header.Set("Sec-Fetch-Site", tt.fetchSite)
}
if tt.origin != "" {
req.Header.Set("Origin", tt.origin)
}
resp, err := app.Test(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != tt.wantStatus {
t.Errorf("status = %d, want %d", resp.StatusCode, tt.wantStatus)
}
})
}
}
Internal Referencesβ
- CSRF Middleware: Cross-Origin Protection Without Tokens
- Ctx: Endpoint
- CORS Middleware
- Helmet Middleware
- Security Middleware Stack
- Give Your Search Endpoint a Body With HTTP QUERY
- Reverse Proxy Setup
- Fiber v3.6.0 release
- Fiber v3.6.1 release
- Add csrf.NewCrossOriginProtection (#4596)
- Fetch metadata (MDN)
- A modern approach to preventing CSRF in Go (Alex Edwards)
