Here's a complete example of how to implement the described middleware chain in Go using Gin, including:
- JWT validation (using
github.com/golang-jwt/jwt)
- Role caching with Redis
- Role-based access control
✅ Prerequisites
Make sure you have these installed:
- Go 1.21+
- Redis server running locally or remotely
- Gin (
go get -u github.com/gin-gonic/gin)
- JWT package:
go get -u github.com/golang-jwt/jwt/v5
- Redis client:
go get -u github.com/go-redis/redis/v8
🧩 Middleware Chain Design
Middleware order:
- Validate JWT token and extract user claims.
- Use user ID from JWT to fetch roles from Redis cache.
- Check if role is sufficient; abort if not.
🔐 Example JWT Claims Structure
go
type Claims struct {
UserID string `json:"user_id"`
Role string `json:"role"`
jwt.RegisteredClaims
}
📦 Full Code Example
main.go
go
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"github.com/golang-jwt/jwt/v5"
"log"
"net/http"
"strings"
"time"
)
var (
JWTSecretKey = []byte("your-secret-key")
rdb *redis.Client
ctx = context.Background()
)
func init() {
// Initialize Redis client
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
if err := rdb.Ping(ctx).Err(); err != nil {
log.Fatalf("Could not connect to Redis: %v", err)
}
}
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
tokenString := c.GetHeader("Authorization")
if tokenString == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
return
}
// Remove Bearer prefix if present
tokenString = strings.TrimPrefix(tokenString, "Bearer ")
// Parse token
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return JWTSecretKey, nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
// Save userID in context for next middlewares
c.Set("userID", claims.UserID)
c.Next()
}
}
func RoleMiddleware(requiredRole string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, exists := c.Get("userID")
if !exists {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "userID not found in context"})
return
}
// Try to get role from Redis
cachedRole, err := rdb.Get(ctx, fmt.Sprintf("user:role:%s", userID)).Result()
if err == redis.Nil {
// Role not cached — simulate fetching from DB
cachedRole = "admin" // Replace this with real DB lookup
err = rdb.Set(ctx, fmt.Sprintf("user:role:%s", userID), cachedRole, 5*time.Minute).Err()
if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "failed to cache role"})
return
}
} else if err != nil {
c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "Redis error"})
return
}
if cachedRole != requiredRole {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "insufficient role"})
return
}
c.Next()
}
}
func ProtectedHandler(c *gin.Context) {
userID, _ := c.Get("userID")
c.JSON(http.StatusOK, gin.H{
"message": "Access granted",
"userID": userID,
})
}
func main() {
r := gin.Default()
protected := r.Group("/api")
protected.Use(AuthMiddleware(), RoleMiddleware("admin")) // Require admin role
{
protected.GET("/protected", ProtectedHandler)
}
log.Println("Server running on :8080")
r.Run(":8080")
}
🧪 Test It Out
Generate a JWT Token (e.g., using https://jwt.io)
Example payload:
json
{
"user_id": "12345",
"role": "admin",
"exp": 1735689600
}
Use secret key: your-secret-key
Send Request:
bash
curl -H "Authorization: Bearer <your_jwt_token>" http://localhost:8080/api/protected
- If role != admin → returns 403 Forbidden
- If valid admin JWT → returns 200 OK
✅ Summary
This solution demonstrates:
- Middleware flow: Authentication → Role check → Handler
- JWT parsing and validation
- Redis caching of user roles
- Abort logic based on insufficient permissions
Let me know if you'd like a version using net/http instead of Gin!