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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Returning a closure lets middleware capture configuration like the valid token while matching Gin's HandlerFunc signature.
  2. 2Calling AbortWithStatusJSON plus return stops downstream handlers from ever executing on a failed check.
  3. 3Validating presence, format, and value as separate stages yields precise status codes for each failure mode.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a bearer-token auth middleware in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code