Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 39 ยท Authentication and Security

CORS, CSRF and Security Headers in Gin

Configure CORS correctly in Gin, understand preflight requests, defend against CSRF with SameSite cookies and tokens, and add security headers like CSP and HSTS.

Browsers enforce rules that protect users from malicious pages: one site may not freely read another site's responses, and cookies are sent automatically even when a request is triggered by a different site. Your Gin API has to cooperate with these rules. Three topics come up in nearly every project: CORS (letting your own front end call the API), CSRF (stopping other sites from making your users' browsers act) and security headers (telling the browser to be strict). They are confused all the time, so this lesson separates them.

Gin and gin-contrib/cors do not run in the in-page runner; their code is read-only. The runnable examples implement the same logic with net/http and httptest so you can see headers and status codes.

Same-origin policy and CORS

An origin is scheme + host + port. https://app.example.com and https://api.example.com are different origins. By default JavaScript on one origin cannot read responses from another. Cross-Origin Resource Sharing (CORS) is how the server opts in: it answers with headers naming the origins that may read its responses.

CORS is enforced by the browser, and it protects the reader, not your server. curl, Postman and attackers' servers ignore it entirely, so it is never a replacement for authentication.

Simple and preflighted requests

A "simple" request (GET, POST with a form content type, no custom headers) is sent directly, and the browser checks the response headers. Anything else, such as PUT, DELETE, JSON bodies or an Authorization header, first triggers a preflight: an OPTIONS request asking permission.

sequenceDiagram
    participant B as Browser (app.example.com)
    participant A as API (api.example.com)
    B->>A: OPTIONS /items (Origin, Access-Control-Request-Method: PUT)
    A-->>B: 204 (Allow-Origin, Allow-Methods, Allow-Headers, Max-Age)
    B->>A: PUT /items/1 (Origin, Authorization)
    A-->>B: 200 (Allow-Origin)

Preflight first, then the real request.

The library

Go
import "github.com/gin-contrib/cors"

r.Use(cors.New(cors.Config{
	AllowOrigins:     []string{"https://app.example.com"},
	AllowMethods:     []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
	AllowHeaders:     []string{"Authorization", "Content-Type"},
	ExposeHeaders:    []string{"X-Request-Id"},
	AllowCredentials: true,
	MaxAge:           12 * time.Hour,
}))

Rules that trip people up:

  • List exact origins. AllowAllOrigins (*) is fine for a fully public read-only API, but cannot be combined with credentials: the browser rejects Access-Control-Allow-Origin: * when cookies are involved.
  • Never reflect the request's Origin blindly: that is "allow everyone" in disguise, with credentials.
  • Register the CORS middleware before your auth middleware, so preflight OPTIONS requests (which carry no token) get answered instead of rejected with 401.
  • A CORS failure appears in the browser console, while your server logs look perfectly fine, because the response was sent.

CORS logic, runnable

Go A CORS middleware that answers preflight

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The evil origin simply gets no Allow-Origin header, so the browser refuses to hand the response to its scripts.

CSRF: cross-site request forgery

CORS stops other sites from reading your API. CSRF is a different attack: a page on evil.example makes the victim's browser send a request to your site, for example by auto-submitting a form to POST https://bank.example/transfer. If the user is logged in with a cookie, the browser attaches that cookie, and the server cannot tell the request was not intended. The attacker cannot read the answer, but the money has already moved.

Defences, from simplest to strongest:

  1. SameSite cookies. Lax (browser default today) withholds the cookie on cross-site POST requests. Use Strict for sensitive cookies. This kills most CSRF by itself.
  2. Never change state with GET. Links and images fire GET requests from any page.
  3. CSRF tokens. The server issues a random token bound to the session; every state-changing request must echo it (form field or header). The attacker's page cannot read it.
  4. Check Origin/Referer (or Sec-Fetch-Site) on unsafe methods and reject foreign origins.
  5. Token auth with the Authorization header (not cookies) is immune, since browsers do not attach it automatically.

For server-rendered Gin forms, github.com/utrack/gin-csrf or gorilla/csrf produce tokens; in JSON APIs using cookies, the double-submit cookie plus header pattern is common.

Go A CSRF token check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Security headers

A few response headers make browsers refuse risky behaviour. Add them in one middleware:

Go
func SecurityHeaders() gin.HandlerFunc {
	return func(c *gin.Context) {
		h := c.Writer.Header()
		h.Set("X-Content-Type-Options", "nosniff")
		h.Set("X-Frame-Options", "DENY")
		h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
		h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
		h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'")
		h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
		c.Next()
	}
}
  • nosniff stops browsers from guessing a file's type (helps with the upload risks in File Uploads and Downloads).
  • X-Frame-Options / frame-ancestors prevent clickjacking (your page inside a hidden frame).
  • Strict-Transport-Security (HSTS) tells browsers to use HTTPS only. Send it only on HTTPS, and start with a short max-age.
  • Content-Security-Policy limits where scripts, styles and images may load from, the strongest defence-in-depth against XSS. Start with report-only mode, then enforce.
  • Referrer-Policy limits what URL leaks to other sites.

For a JSON API most of these are cheap insurance; for HTML pages, CSP deserves real attention. Also consider gin.SetTrustedProxies when behind a load balancer so c.ClientIP() cannot be spoofed with X-Forwarded-For.

Common mistakes

  • Treating CORS as authentication or as protection for the server.
  • Allow-Origin: * together with credentials (browsers refuse) or reflecting any origin.
  • Auth middleware registered before CORS, so preflights fail with 401.
  • Disabling CSRF protection because "we use JSON": cookie-authenticated JSON endpoints are still vulnerable without SameSite/tokens.
  • Changing data with GET routes.
  • Copying a strict CSP and then allowing 'unsafe-inline' everywhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Who enforces CORS?

    The server only sends headers; the browser decides whether scripts may read the response. curl ignores CORS.
  2. 2. Why register the CORS middleware before auth middleware?

    If auth runs first, the preflight gets 401 and the browser blocks the real request.
  3. 3. What does a CSRF attack exploit?

    The victim's browser sends the authenticated request, so the server sees valid cookies.
  4. 4. Which is the first line of defence against CSRF for cookie sessions?

    SameSite stops browsers from sending the cookie on most cross-site requests. Tokens add depth.
  5. 5. What does X-Content-Type-Options: nosniff do?

    It makes the browser trust the declared Content-Type, preventing some script-injection tricks.

Summary

  • CORS lets the browser share responses with named origins; preflight handles non-simple requests; it is not authentication.
  • CSRF abuses automatic cookies; use SameSite, tokens, origin checks and POST/PUT/DELETE for changes.
  • Add security headers (nosniff, frame protection, HSTS, CSP, referrer policy) in one middleware.
  • Order middleware deliberately: CORS before auth.

Next: Rate Limiting and Input Safety