go 50 lines · 8 steps

Timing-safe API key auth in Gin

A Gin middleware validates per-client API keys with a constant-time comparison, then guards a route group.

Explained by highlit
1package middleware
2 
3import (
4 "crypto/subtle"
5 "net/http"
6 "strings"
7 
8 "github.com/gin-gonic/gin"
9)
10 
11func APIKeyAuth(validKeys map[string]string) gin.HandlerFunc {
12 return func(c *gin.Context) {
13 apiKey := strings.TrimSpace(c.GetHeader("X-API-Key"))
14 if apiKey == "" {
15 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
16 "error": "missing required header: X-API-Key",
17 })
18 return
19 }
20 
21 clientID := strings.TrimSpace(c.GetHeader("X-Client-Id"))
22 if clientID == "" {
23 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
24 "error": "missing required header: X-Client-Id",
25 })
26 return
27 }
28 
29 expected, ok := validKeys[clientID]
30 if !ok || subtle.ConstantTimeCompare([]byte(expected), []byte(apiKey)) != 1 {
31 c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
32 "error": "invalid API key for client",
33 })
34 return
35 }
36 
37 c.Set("clientID", clientID)
38 c.Next()
39 }
40}
41 
42func RegisterRoutes(r *gin.Engine, keys map[string]string, h *Handler) {
43 api := r.Group("/v1")
44 api.Use(APIKeyAuth(keys))
45 {
46 api.GET("/orders", h.ListOrders)
47 api.POST("/orders", h.CreateOrder)
48 api.GET("/orders/:id", h.GetOrder)
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning a closure over configuration lets middleware carry per-app state like valid keys.
  2. 2Comparing secrets with subtle.ConstantTimeCompare avoids leaking key length or content through timing.
  3. 3Aborting early with a JSON error stops the handler chain, while c.Set passes verified identity downstream.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Timing-safe API key auth in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code