CSRF Protection
Browsers attach cookies to requests automatically. A hostile page can submit a request with those credentials. Protect state-changing browser routes with webmiddleware.CSRFWithConfig, including login and logout. Authentication checks who the user is. CSRF checks require a token that the calling page can read.
Auth and the templ + htmx starter UI do not automatically install this middleware. Apply it explicitly in app/routes.go and update your client together. SameSite cookies and CORS are additional policies, not replacements for the token check.
Add Protected Browser Routes
Start with a Web API app. Add this complete file as app/browser_routes.go. The POST acknowledges a demonstration request. Replace its handler with your own application behavior after checking the token flow.
package app
import (
"net/http"
"github.com/goforj/web"
"github.com/goforj/web/webmiddleware"
)
// browserRoutes keeps token issuance and validation under the same cookie policy.
func browserRoutes(secureCookies bool) web.RouteGroup {
csrf := webmiddleware.CSRFWithConfig(webmiddleware.CSRFConfig{
TokenLookup: "header:X-CSRF-Token",
ContextKey: "csrf",
CookieName: "_csrf",
CookiePath: "/",
CookieSecure: secureCookies,
CookieHTTPOnly: true,
CookieSameSite: http.SameSiteLaxMode,
})
return web.NewRouteGroup("/browser", []web.Route{
web.NewRoute(http.MethodGet, "/csrf", csrfToken),
web.NewRoute(http.MethodPost, "/preferences", savePreference),
}, csrf)
}
// csrfToken exposes the request token without allowing shared caches to retain it.
func csrfToken(r web.Context) error {
r.SetHeader("Cache-Control", "no-store")
return r.Text(http.StatusOK, r.Get("csrf").(string))
}
// savePreference acknowledges a request after the route group validates its token.
func savePreference(r web.Context) error {
return r.NoContent(http.StatusNoContent)
}In the slice returned by ProvideRoutes in app/routes.go, add browserRoutes(false) beside the existing groups for this plain-HTTP local check. Use browserRoutes(true) for production HTTPS. This setting controls the CSRF cookie separately from AUTH_COOKIE_SECURE.
The demonstration endpoint has no account data. For real account changes, also apply authService.RequireAuth to the relevant routes. Apply CSRF checks to your existing cookie-authenticated groups and login handlers too. Protecting /browser does not protect other groups.
Verify the Token Check
Start the app with forj dev. In another terminal, request a token and send it back with the cookie. Use your configured HTTP port if you changed it.
csrf_jar="$(mktemp)"
trap 'rm -f "$csrf_jar"' EXIT
csrf_token="$(curl -fsS -c "$csrf_jar" http://localhost:3000/browser/csrf)"
curl -sS -o /dev/null -w '%{http_code}\n' \
-b "$csrf_jar" -X POST http://localhost:3000/browser/preferences
# 403
curl -sS -o /dev/null -w '%{http_code}\n' \
-b "$csrf_jar" -H "X-CSRF-Token: $csrf_token" \
-X POST http://localhost:3000/browser/preferences
# 204The first POST fails because the header is missing. The second succeeds because its header matches the cookie token. Changing the header value must return 403 too.
Send the Token from the Browser
For a same-origin JavaScript client, fetch the token before a mutation. JavaScript reads the token from the response, and the CSRF cookie stays HttpOnly.
const tokenResponse = await fetch('/browser/csrf', { credentials: 'same-origin' })
if (!tokenResponse.ok) throw new Error('Could not obtain a CSRF token')
const token = await tokenResponse.text()
const response = await fetch('/browser/preferences', {
method: 'POST',
credentials: 'same-origin',
headers: { 'X-CSRF-Token': token },
})
if (!response.ok) throw new Error('Preference request failed')For server-rendered forms, configure TokenLookup: "form:_csrf" and render r.Get("csrf") into a hidden _csrf input with your template engine's escaping. The form's GET and POST must both pass through the middleware. With htmx, send X-CSRF-Token on mutation requests or include the configured form field.
Protect Side Effects
The middleware permits safe methods without a token, so never mutate application state through GET. Keep the CSRF cookie host-scoped and use HTTPS in production. Restrict credentialed cross-origin access to trusted origins. Do not log token values or cache token responses in a shared cache.
If you exempt a webhook from browser CSRF checks, authenticate it through the provider's signature verification and keep the exemption limited to that route. Continue with middleware placement and session policy.