go
40 lines · 5 steps
Building a bearer-token auth middleware in Gin
A Gin middleware that validates an Authorization header and aborts the request chain when authentication fails.
Explained by
highlit
1package middleware
2
3import (
4 "net/http"
5 "strings"
6
7 "github.com/gin-gonic/gin"
8)
9
10// AuthRequired validates the bearer token and aborts the request chain
11// early when authentication fails, so downstream handlers never run.
12func AuthRequired(validToken string) gin.HandlerFunc {
13 return func(c *gin.Context) {
14 header := c.GetHeader("Authorization")
15 if header == "" {
16 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
17 "error": "missing Authorization header",
18 })
19 return
20 }
21
22 parts := strings.SplitN(header, " ", 2)
23 if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
24 c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
25 "error": "malformed Authorization header",
26 })
27 return
28 }
29
30 if parts[1] != validToken {
31 c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
32 "error": "invalid token",
33 })
34 return
35 }
36
37 c.Set("authenticated", true)
38 c.Next()
39 }
40}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning a closure lets middleware capture configuration like the valid token while matching Gin's HandlerFunc signature.
- 2Calling AbortWithStatusJSON plus return stops downstream handlers from ever executing on a failed check.
- 3Validating presence, format, and value as separate stages yields precise status codes for each failure mode.
Related explainers
go
package main import ( "errors"
Parsing and validating CLI flags in Go
cli-parsing
validation
error-handling
Intermediate
8 steps
go
package cache import ( "container/list"
Building a generic LRU cache in Go
lru-cache
generics
linked-list
Intermediate
8 steps
python
import time from collections import defaultdict from threading import Lock
Sliding-window login rate limiting in Flask
rate-limiting
sliding-window
thread-safety
Intermediate
7 steps
javascript
const RATE_LIMIT = 100; const WINDOW_MS = 60 * 1000; const BLOCK_MS = 5 * 60 * 1000;
Building a rate-limiting middleware in Express
rate-limiting
middleware
closures
Intermediate
9 steps
go
package model import ( "encoding/json"
Custom JSON marshaling in Go
json
serialization
interfaces
Intermediate
5 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 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/building-a-bearer-token-auth-middleware-in-gin-explained-go-6007/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.