Gin in production · 5 MIN READ
CORS by hand in Gin: an exact origin allow-list, real preflights and Vary: Origin
Implement CORS middleware that answers preflights, echoes only allow-listed origins, sets Vary correctly and is never mistaken for access control.
CORS is the protocol a server uses to tell a browser which other origins may read its responses. It relaxes the same-origin policy; it never tightens it. Done carelessly it either breaks a legitimate front end or lets any website read a signed-in user's data. Done correctly it is still not authentication, authorization or CSRF protection, and the server has to keep enforcing those on its own.
gin · A MAP OF THE IDEA
- Add Vary: Origin
- Match exact allow-list
- Answer preflight with 204
- Server still authorizes
Useful when
- Exact origins and validated config make the policy reviewable.
- Engine-level middleware handles preflights without OPTIONS routes.
Watch out
- CORS does not stop non-browser clients or CSRF form posts.
- Group-scoped CORS middleware never sees unmatched OPTIONS preflights.
Implementation & operation cost: A small middleware and a list of origins to maintain per environment; the risk is in the configuration, so test it like code.
What the browser asks and what the server decides
Simple requests, such as a GET or a form POST with no custom headers, are sent straight to the server with an Origin header; afterwards the browser checks Access-Control-Allow-Origin to decide whether page script may read the answer. Anything else, such as PUT, DELETE, a JSON content type or an Authorization header, first triggers a preflight: an OPTIONS request carrying Access-Control-Request-Method and Access-Control-Request-Headers. The browser sends the real request only if the preflight response approves that origin, method and set of headers. For a simple request the handler has already run by the time the browser decides, so CORS controls who may read a response, not who may send a request. Requests made with credentials, meaning cookies or fetch with credentials: "include", additionally need Access-Control-Allow-Credentials: true and an explicit origin.
An allow-list middleware that answers preflights
The middleware runs engine-wide. It adds Vary: Origin to every response, echoes an allow-listed origin exactly, and terminates preflights itself with 204 so no handler runs. The constructor validates configuration, so the dangerous combinations fail at startup instead of in a browser console. Five requests show an approved preflight, a refused one, a credentialed GET, a GET from an unknown origin and a GET with no Origin at all.
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
)
type CORSConfig struct {
Origins []string // exact scheme://host[:port] values
Methods []string // methods a preflight may ask for
Headers []string // request headers a preflight may ask for
Credentials bool // allow cookies or Authorization from the page
MaxAge time.Duration
}
func newCORS(cfg CORSConfig) (gin.HandlerFunc, error) {
origins := map[string]bool{}
for _, o := range cfg.Origins {
if o == "*" && cfg.Credentials {
return nil, errors.New(`cors: "*" cannot be combined with credentials`)
}
if o == "null" {
return nil, errors.New(`cors: never allow the "null" origin`)
}
origins[o] = true
}
headers := map[string]bool{}
for _, h := range cfg.Headers {
headers[strings.ToLower(h)] = true
}
allowMethods := strings.Join(cfg.Methods, ", ")
allowHeaders := strings.Join(cfg.Headers, ", ")
maxAge := strconv.Itoa(int(cfg.MaxAge / time.Second))
return func(c *gin.Context) {
h := c.Writer.Header()
// The response depends on Origin whether or not one was sent.
h.Add("Vary", "Origin")
origin := c.GetHeader("Origin")
preflight := c.Request.Method == http.MethodOptions &&
c.GetHeader("Access-Control-Request-Method") != ""
if preflight {
h.Add("Vary", "Access-Control-Request-Method")
h.Add("Vary", "Access-Control-Request-Headers")
}
allowed := origin != "" && (origins[origin] || origins["*"])
if !allowed {
if preflight {
c.AbortWithStatus(http.StatusForbidden)
return
}
c.Next() // no CORS headers: the browser hides the response from the page
return
}
if origins["*"] {
h.Set("Access-Control-Allow-Origin", "*")
} else {
h.Set("Access-Control-Allow-Origin", origin)
}
if cfg.Credentials {
h.Set("Access-Control-Allow-Credentials", "true")
}
if !preflight {
c.Next()
return
}
if !slices.Contains(cfg.Methods, c.GetHeader("Access-Control-Request-Method")) {
c.AbortWithStatus(http.StatusForbidden)
return
}
for name := range strings.SplitSeq(c.GetHeader("Access-Control-Request-Headers"), ",") {
if name = strings.ToLower(strings.TrimSpace(name)); name != "" && !headers[name] {
c.AbortWithStatus(http.StatusForbidden)
return
}
}
h.Set("Access-Control-Allow-Methods", allowMethods)
h.Set("Access-Control-Allow-Headers", allowHeaders)
h.Set("Access-Control-Max-Age", maxAge)
c.AbortWithStatus(http.StatusNoContent)
}, nil
}
func show(r http.Handler, method, origin string, extra ...string) {
req := httptest.NewRequest(method, "/api/notes", nil)
if origin != "" {
req.Header.Set("Origin", origin)
}
for i := 0; i+1 < len(extra); i += 2 {
req.Header.Set(extra[i], extra[i+1])
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
line := fmt.Sprintf("%s from %q: %d", method, origin, w.Code)
if body := w.Body.String(); body != "" {
line += " " + body
}
fmt.Println(line)
for _, k := range []string{"Access-Control-Allow-Origin", "Access-Control-Allow-Credentials",
"Access-Control-Allow-Methods", "Access-Control-Allow-Headers", "Access-Control-Max-Age"} {
if v := w.Header().Get(k); v != "" {
fmt.Printf(" %s: %s\n", k, v)
}
}
fmt.Printf(" Vary: %s\n", strings.Join(w.Header().Values("Vary"), ", "))
}
func main() {
gin.SetMode(gin.TestMode)
if _, err := newCORS(CORSConfig{Origins: []string{"*"}, Credentials: true}); err != nil {
fmt.Println("rejected config:", err)
}
cors, err := newCORS(CORSConfig{
Origins: []string{"https://app.example.com"},
Methods: []string{"GET", "POST", "PUT", "DELETE"},
Headers: []string{"Authorization", "Content-Type"},
Credentials: true,
MaxAge: 10 * time.Minute,
})
if err != nil {
panic(err)
}
r := gin.New()
r.Use(cors) // engine-wide, so it also runs for OPTIONS requests that match no route
r.GET("/api/notes", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"notes": 3}) })
show(r, "OPTIONS", "https://app.example.com",
"Access-Control-Request-Method", "PUT",
"Access-Control-Request-Headers", "authorization,content-type")
show(r, "OPTIONS", "https://evil.example", "Access-Control-Request-Method", "PUT")
show(r, "GET", "https://app.example.com")
show(r, "GET", "https://evil.example")
show(r, "GET", "")
}newCORS rejects "*" combined with credentials and the "null" origin before any request is served. Inside the middleware, Header().Add appends to Vary rather than overwriting a value another layer set. A preflight is an OPTIONS request that carries Access-Control-Request-Method; the requested method and every requested header are checked against the configured lists, lowercased because header names are case-insensitive, and the allowed preflight ends with AbortWithStatus(204). No OPTIONS route is registered, yet the preflight still reaches the middleware because r.Use also attaches it to Gin's 404 chain. The evil.example preflight is refused with 403. Its simple GET still gets 200 and the JSON body, only without CORS headers.
Vary: Origin and the wildcard rule
When the response echoes the caller's origin, its headers depend on the Origin request header, and caches must know that. Without Vary: Origin, a shared cache or the browser's own HTTP cache can store the copy made for app.example.com and replay it to another origin, or store the copy made for a request with no Origin and replay it to a cross-origin fetch, which then fails with an error that looks random. So add Vary: Origin to every response from CORS-enabled routes, including refusals and requests without an Origin header. The wildcard means any origin may read, and browsers reject it for credentialed requests. The tempting workaround, reflecting whatever Origin arrives while also sending Allow-Credentials: true, is worse than the wildcard: it lets every website read the user's authenticated data. Never allow-list the null origin either, because sandboxed iframes and local files send it and an attacker can produce it on purpose. Compare whole origins exactly; strings.HasSuffix(origin, "example.com") also accepts https://evilexample.com.
Preflight routing and max-age in Gin
Gin runs a group's middleware only for routes that matched. A preflight for /api/notes matches nothing unless an OPTIONS route exists, so CORS middleware attached to the api group never sees it and Gin answers 404, or 405 when HandleMethodNotAllowed is enabled. Middleware registered with Engine.Use is also part of the 404 and 405 handler chains, which is why the program registers CORS there. Access-Control-Max-Age lets the browser cache an approved preflight. Without it the default is 5 seconds, and browsers cap whatever you send: Firefox at 24 hours, current Chromium at 2 hours. Ten minutes removes most preflight round trips while still letting a configuration change take effect quickly. Check Access-Control-Request-Headers against a list instead of echoing it back, so a front end cannot quietly start sending headers nobody has reviewed. The same applies to Access-Control-Expose-Headers: list response headers such as ETag explicitly if page script needs to read them.
What CORS does not protect
The 200 for https://evil.example in the output is the key point: the handler ran and produced data, and only the browser declined to hand it to the page. curl, server-side scripts and attack tools ignore CORS, so every endpoint must still authenticate and authorize each request itself. CORS also does not stop cross-site request forgery. A form POST, or a simple fetch that carries cookies, is sent cross-origin without a preflight and the server performs the side effect; the attacker only loses the ability to read the reply. Cookie-authenticated APIs therefore need CSRF defenses: SameSite cookies, a synchronizer or double-submit token, or rejecting state-changing requests whose Origin or Sec-Fetch-Site header names another site. Bearer tokens sent in an Authorization header are not attached by the browser automatically, which is why they avoid classic CSRF. When reviewing a CORS change, test an approved and a refused preflight, a disallowed method and header, a credentialed request, the presence of Vary on every response and the configuration checks.
TAKE THIS WITH YOU
CORS relaxes the browser's read barrier for an exact list of origins: answer preflights at the engine level, echo the origin together with Vary: Origin, never pair * or a reflected origin with credentials, and keep authentication and CSRF defenses on the server.
Check your understanding
Can a server answer a credentialed request with Access-Control-Allow-Origin: * and still let the page read the response?
Go to the source
Progress stays in this browser. No account needed.