Gin in production · 6 MIN READ

Bearer authentication in Gin: verify once at the group boundary, hand handlers a typed principal

Write middleware that verifies an HMAC-signed bearer token, stores a typed principal and answers 401 or 403 for the right reasons.

Authentication middleware turns an Authorization header into one of two outcomes before any handler runs: a verified principal, or a refusal the client can act on. The bugs live at the edges of that job: a route registered outside the protected group, a MAC compared with ==, a 403 where the client needed a 401, or a debug log that quietly archives every credential it sees.

gin · A MAP OF THE IDEA

  1. Parse Authorization
  2. Verify MAC with hmac.Equal
  3. Store typed principal
  4. Check scope per group

Useful when

  • One verification point covers every route in the group.
  • Handlers receive a typed principal instead of raw headers.

Watch out

  • Routes registered outside the group, or before Use, are public.
  • Stateless HMAC tokens cannot be revoked before expiry without extra state.

Implementation & operation cost: One HMAC per request is cheap; the real cost is key management: rotation, storage in a secret manager and a revocation story.

01

Decide what the middleware owns

Authentication answers who is calling; authorization answers whether that caller may do this. Keep them in separate middleware so each has one reason to refuse. A 401 Unauthorized means the request carried no usable credentials and a retry with valid ones may succeed; RFC 9110 requires a WWW-Authenticate header on every 401 so the client learns which scheme to use. A 403 Forbidden means the server knows exactly who is calling and the answer is still no, so logging in again will not help. RFC 6750 refines this for bearer tokens: a request with no token gets a bare challenge, an invalid or expired token gets error="invalid_token", and a valid token without the needed scope gets 403 with error="insufficient_scope". Neither middleware decides whether note 7 belongs to user-42. That ownership check needs the stored data, so it belongs to the use case, which receives the principal as an argument.

02

Verify the MAC first, then trust the payload

An opaque token is a string the client stores and sends back but never interprets. Here it is base64url(subject|scopes|expiry) followed by a dot and an HMAC-SHA256 tag over those bytes, keyed with a server secret. The verifier recomputes the tag and compares it with hmac.Equal, whose running time does not depend on where the first differing byte is; == on strings or bytes.Equal may stop early and leak how much of a guess was right. Only a payload with a valid tag is parsed, and expiry is checked against an injected clock so tests never sleep. The program forges an admin token by swapping the payload while keeping a real tag, and replays an expired one.

go
package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"os"
	"slices"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// Principal is everything downstream code may know about the caller.
type Principal struct {
	Subject string
	Scopes  []string
}

// principalKey is unexported, so no other package can overwrite the value.
type principalKey struct{}

var (
	errMalformed = errors.New("malformed token")
	errSignature = errors.New("bad signature")
	errExpired   = errors.New("expired")
)

// Verifier checks tokens shaped base64url(payload) "." base64url(HMAC-SHA256).
type Verifier struct {
	key []byte
	now func() time.Time
}

func (v Verifier) mac(payload []byte) []byte {
	m := hmac.New(sha256.New, v.key)
	m.Write(payload)
	return m.Sum(nil)
}

// Issue exists for the demo; in production a separate login flow issues tokens.
func (v Verifier) Issue(subject, scopes string, exp time.Time) string {
	payload := []byte(subject + "|" + scopes + "|" + strconv.FormatInt(exp.Unix(), 10))
	enc := base64.RawURLEncoding
	return enc.EncodeToString(payload) + "." + enc.EncodeToString(v.mac(payload))
}

func (v Verifier) Verify(token string) (Principal, error) {
	encPayload, encMAC, ok := strings.Cut(token, ".")
	if !ok {
		return Principal{}, errMalformed
	}
	payload, err1 := base64.RawURLEncoding.DecodeString(encPayload)
	got, err2 := base64.RawURLEncoding.DecodeString(encMAC)
	if err1 != nil || err2 != nil {
		return Principal{}, errMalformed
	}
	if !hmac.Equal(got, v.mac(payload)) {
		return Principal{}, errSignature
	}
	// Only a payload with a valid MAC is worth parsing.
	parts := strings.Split(string(payload), "|")
	if len(parts) != 3 {
		return Principal{}, errMalformed
	}
	exp, err := strconv.ParseInt(parts[2], 10, 64)
	if err != nil {
		return Principal{}, errMalformed
	}
	if !v.now().Before(time.Unix(exp, 0)) {
		return Principal{}, errExpired
	}
	return Principal{Subject: parts[0], Scopes: strings.Fields(parts[1])}, nil
}

const realm = `Bearer realm="notes"`

func authenticate(v Verifier, log *slog.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		scheme, token, ok := strings.Cut(c.GetHeader("Authorization"), " ")
		if !ok || !strings.EqualFold(scheme, "Bearer") || token == "" {
			c.Header("WWW-Authenticate", realm)
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
			return
		}
		p, err := v.Verify(token)
		if err != nil {
			// Log the route and the reason, never the credential.
			log.Info("auth rejected", "route", c.FullPath(), "reason", err.Error())
			c.Header("WWW-Authenticate", realm+`, error="invalid_token"`)
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
			return
		}
		c.Set(principalKey{}, p)
		c.Next()
	}
}

func principalFrom(c *gin.Context) (Principal, bool) {
	v, ok := c.Get(principalKey{})
	if !ok {
		return Principal{}, false
	}
	p, ok := v.(Principal)
	return p, ok
}

func requireScope(scope string) gin.HandlerFunc {
	return func(c *gin.Context) {
		p, ok := principalFrom(c)
		if !ok {
			// A route was wired without authenticate: fail closed.
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		if !slices.Contains(p.Scopes, scope) {
			c.Header("WWW-Authenticate", realm+`, error="insufficient_scope", scope="`+scope+`"`)
			c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "insufficient scope"})
			return
		}
		c.Next()
	}
}

func newRouter(v Verifier, log *slog.Logger) *gin.Engine {
	r := gin.New()
	r.GET("/healthz", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"status": "ok"}) })

	api := r.Group("/api", authenticate(v, log))
	api.GET("/notes", func(c *gin.Context) {
		p, _ := principalFrom(c)
		c.JSON(http.StatusOK, gin.H{"owner": p.Subject})
	})
	admin := api.Group("/admin", requireScope("notes:admin"))
	admin.DELETE("/notes/:id", func(c *gin.Context) { c.Status(http.StatusNoContent) })
	return r
}

func main() {
	gin.SetMode(gin.TestMode)
	now := time.Unix(1_800_000_000, 0)
	// Test key only. A real key comes from a secret store and is rotated.
	v := Verifier{key: []byte("test-only-key-0123456789abcdef!!"), now: func() time.Time { return now }}
	log := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey && len(groups) == 0 {
				return slog.Attr{}
			}
			return a
		},
	}))
	r := newRouter(v, log)

	reader := v.Issue("user-42", "notes:read", now.Add(15*time.Minute))
	expired := v.Issue("user-42", "notes:read", now.Add(-time.Minute))
	// Swap in an admin payload but keep the reader's MAC.
	forged := base64.RawURLEncoding.EncodeToString([]byte("user-42|notes:read notes:admin|1800000900")) +
		reader[strings.IndexByte(reader, '.'):]

	cases := []struct{ method, path, auth string }{
		{"GET", "/healthz", ""},
		{"GET", "/api/notes", ""},
		{"GET", "/api/notes", "Bearer " + forged},
		{"GET", "/api/notes", "Bearer " + expired},
		{"GET", "/api/notes", "bearer " + reader},
		{"DELETE", "/api/admin/notes/7", "Bearer " + reader},
	}
	for _, tc := range cases {
		req := httptest.NewRequest(tc.method, tc.path, nil)
		if tc.auth != "" {
			req.Header.Set("Authorization", tc.auth)
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Println(tc.method, tc.path, w.Code, w.Body.String())
		if h := w.Header().Get("WWW-Authenticate"); h != "" {
			fmt.Println("  WWW-Authenticate:", h)
		}
	}
}
Read the code

Verify splits at the first dot, decodes both halves and recomputes the tag before parsing anything, so the forged admin payload fails as a bad signature without its scopes ever being read. authenticate compares the scheme with strings.EqualFold because auth schemes are case-insensitive, which is why the lowercase bearer request succeeds. Each refusal sets WWW-Authenticate before AbortWithStatusJSON writes the response, and the rejection log line carries the route and a reason code but no token. c.Set stores the Principal under the unexported principalKey type, and principalFrom is the only reader, so handlers get a typed value instead of re-parsing headers. requireScope runs inside the admin group, after authenticate, and answers 403 with insufficient_scope. The JSON log handler drops the time attribute so the output is stable.

03

Public and protected routes are a wiring decision

The route group is the policy boundary: anything registered on api passes through authenticate, anything registered on r is public, whether or not that was intended. Gin copies a group's middleware into each route's handler chain at registration time, so calling api.Use(authenticate) after a route was added does not protect that earlier route; it keeps answering 200 to anonymous callers. Pass middleware to Group or call Use before registering routes, and make the gap testable. r.Routes() lists every registered method and path, which lets one test send an anonymous request to each route outside a short public allow-list and fail when any of them answers something other than 401.

go
// In auth_test.go: every route outside the public allow-list must refuse anonymous calls.
func TestRoutesRequireAuth(t *testing.T) {
	gin.SetMode(gin.TestMode)
	r := newRouter(testVerifier(), slog.New(slog.DiscardHandler))
	public := map[string]bool{"GET /healthz": true}
	for _, rt := range r.Routes() {
		if public[rt.Method+" "+rt.Path] {
			continue
		}
		w := httptest.NewRecorder()
		r.ServeHTTP(w, httptest.NewRequest(rt.Method, rt.Path, nil))
		if w.Code != http.StatusUnauthorized {
			t.Errorf("%s %s answered %d without a token", rt.Method, rt.Path, w.Code)
		}
	}
}
Read the code

This fragment is a go test that runs in your own project, next to newRouter. testVerifier is a helper that builds a Verifier with a fixed test key and clock, and slog.DiscardHandler keeps the rejection logs out of the test output. A path such as /api/admin/notes/:id is sent literally, which still matches the parameterized route with id set to ":id". New routes are covered automatically, so a forgotten group fails CI instead of production.

04

Keep credentials out of logs, URLs and error bodies

A bearer token is a password with an expiry date: anyone who copies it from a log file can replay it until then. Log a stable reason code such as bad signature or expired, never the header value, and keep the public response generic so clients cannot tell a forged token from an expired one. Do not accept tokens in query strings: gin.Logger records the path together with the raw query unless SkipQueryString is set, and proxies and browser history keep URLs too. Gin's Recovery middleware in debug mode dumps the request headers with only Authorization masked, so a Cookie header is printed as is. Routing every log through one redaction step, covered in the request-logging lesson, is safer than auditing each call site.

05

What a production verifier adds

This verifier is a model; it shows the order of checks, not a complete token system. Real deployments rotate keys, so prefix tokens with a key ID and accept the previous key for one token lifetime. A stateless HMAC token cannot be revoked before it expires, so keep lifetimes short or, when instant logout matters, issue random tokens and store their SHA-256 hash in a session table you can delete from, at the cost of one lookup per request. Load keys of at least 32 random bytes from a secret manager and use a separate key per purpose. The pipe separator only works because the issuer controls the subject; use a structured encoding for anything richer, or a vetted JWT or PASETO library that pins the algorithm. Test missing, malformed, forged, expired, wrong-scope and lowercase-scheme tokens as separate cases, and assert on headers and body as well as on the status.

TAKE THIS WITH YOU

Authenticate at the group boundary, compare MACs with hmac.Equal before parsing anything, store a typed principal under an unexported key, answer 401 with WWW-Authenticate for bad credentials and 403 for missing permission, and never log the token.

Check your understanding

A caller sends a valid, unexpired bearer token that lacks the notes:admin scope to an admin-only route. What should the middleware answer?

Go to the source

Progress stays in this browser. No account needed.