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 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
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
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.