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
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
go
package scheduler import ( "container/heap"
A priority job queue with Go's container/heap
priority-queue
heap
interfaces
Intermediate
9 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.