Build a Secure JWT‑Based Authentication Middleware in Go Fiber with Rate Limiting and Request Validation

User avatar placeholder
Written by Tamzid Ahmed

October 31, 2026

JWT auth middleware in Go Fiber provides a lightweight, stateless way to secure APIs. In this guide you’ll build a production‑ready middleware that validates JWT tokens, applies rate limiting, and enforces request schemas—all while keeping Go’s performance benefits intact.

Why a JWT Middleware for Fiber?

Fiber’s design mirrors Express, making middleware a first‑class concept. Coupling JWT validation with rate limiting at the middleware level guarantees a single, maintainable entry point for authentication and abuse protection. It also scales horizontally: each worker simply checks a token, never needing to query a database for every request.

Prerequisites & Environment Setup

Before you start, ensure you have the following:

  • Go 1.22 or later (install go install golang.org/dl/go1.22@latest && go1.22 download)
  • Redis v7+ for distributed rate limiting (optional but recommended)
  • GitHub‑hosted or local private key for signing tokens

Create a new module:

  1. mkdir fiber-jwt-demo && cd fiber-jwt-demo
  2. go mod init github.com/yourname/fiber-jwt-demo
  3. go get github.com/gofiber/fiber/v2 github.com/golang-jwt/jwt/v5 github.com/go-playground/validator/v10 github.com/go-redis/redis/v8 golang.org/x/crypto/bcrypt

Choosing the Right JWT Library

The golang-jwt/jwt package is the de‑facto standard. It supports both HMAC and RSA signing and is actively maintained. If your token payloads are large and you need fast claims extraction, github.com/notnil/jwt is an alternative, though it’s less commonly used.

Building the Core Middleware

Step 1: Define Claims and SigningKey

Use a struct for custom claims to avoid the generic jwt.MapClaims overhead.

type CustomClaims struct {
UserID string `json:"sub"`
Role string `json:"role"`
jwt.RegisteredClaims
}

Step 2: Verify Token & Extract Claims

The middleware reads the Authorization header, validates signature, and attaches claims to c.Locals("user") for downstream handlers.

func JWTAuthMiddleware(secret []byte) fiber.Handler {
return func(c *fiber.Ctx) error {
auth := c.Get("Authorization")
if auth == "" {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error":"missing token"})
}
tokenStr := strings.TrimPrefix(auth, "Bearer ")
token, err := jwt.ParseWithClaims(tokenStr, &CustomClaims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fiber.ErrUnauthorized
}
return secret, nil
})
if err != nil || !token.Valid {
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"error":"invalid token"})
}
if claims, ok := token.Claims.(*CustomClaims); ok {
c.Locals("user", claims)
}
return c.Next()
}
}

Step 3: Expose Current User

In handlers, use user := c.Locals("user").(*CustomClaims) for authorization logic.

Integrating Rate Limiting

Adding a second middleware keeps concerns separate yet co‑located.

In‑Memory Counter (single‑node)

Fast but not shared across replicas. Use a sync.Map of burst windows.

Redis‑backed Sliding Window (recommended)

Use github.com/go-redis/redis/v8 to atomically increment a key per client IP and set a TTL.

func RateLimitMiddleware(limit int, duration time.Duration, rdb *redis.Client) fiber.Handler {
return func(c *fiber.Ctx) error {
ip := c.IP()
key := fmt.Sprintf("rl:%s", ip)
count, err := rdb.Incr(c.Context(), key).Result()
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error":"rate limiter error"})
}
if count == 1 {
rdb.Expire(c.Context(), key, duration)
}
if int(count) > limit {
return c.Status(fiber.StatusTooManyRequests).JSON(fiber.Map{"error":"rate limit exceeded"})
}
return c.Next()
}
}

Request Validation Middleware

Automation prevents malformed data from reaching your service. The go-playground/validator package binds structs and validates tags.

Define a DTO

type LoginRequest struct {
Email string `json:"email" validate:"required,email"`
Password string `json:"password" validate:"required,min=8"`
}

Middleware Implementation

func ValidateLoginMiddleware() fiber.Handler {
return func(c *fiber.Ctx) error {
var req LoginRequest
if err := c.BodyParser(&req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error":"invalid JSON"})
}
validate := validator.New()
if err := validate.Struct(req); err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error":err.Error()})
}
c.Locals("request", req)
return c.Next()
}
}

Error Handling & Response Strategy

Keep responses consistent:

  • 401: Unauthorized – missing or expired token
  • 403: Forbidden – claims disallow action
  • 429: Too Many Requests – rate limit hit
  • 400: Bad Request – validation failures

Wrap the middleware chain in a custom fiber.ErrorHandler for logging.

Performance Optimizations

  • Reuse jwt.Parser with jwt.WithoutClaimsValidation() if you only need signature validation.
  • Cache public keys per tenant so jwt.ParseWithClaims doesn’t fetch them on every request.
  • Batch Redis operations when you have multiple rate limit rules.
  • Use c.Locals sparingly to avoid GC overhead on massive requests.

Testing & Edge Cases

Write table‑driven tests covering:

  • Valid token with correct claims
  • Expired token
  • Wrong signing method
  • Missing token and malformed header
  • Rate limit boundaries: first hit, limit exceeded, reset after TTL
  • Invalid payload JSON and field validation errors

Employ httptest servers and github.com/stretchr/testify/assert for readable assertions.

Deployment & Observability

For production:

  • Use github.com/uber-go/zap or github.com/go-logr/logr for structured logs.
  • Expose Prometheus metrics: promhttp.Handler() and custom counters for jwt_valid_total, rate_limit_exceeded_total, etc.
  • Enable TLS on every edge server and enforce HSTS.
  • Rotate RSA keys monthly and implement JWKS endpoint if using external IdPs.

Conclusion

By stitching together a JWT authentication middleware, Redis‑powered rate limiting, and validator‑based request checks, your Go Fiber app gains robust security with minimal friction. Deploy the stack, monitor the metrics, and iterate on key change strategies to keep the system both safe and scalable.

Next step: generate your first signed token and test the full flow locally—then push it to staging and observe the counter metrics.

Leave a Comment