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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning a closure over configuration lets middleware carry per-app state like valid keys.
- 2Comparing secrets with subtle.ConstantTimeCompare avoids leaking key length or content through timing.
- 3Aborting early with a JSON error stops the handler chain, while c.Set passes verified identity downstream.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/timing-safe-api-key-auth-in-gin-explained-go-1810/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.