Fix JWTAuthError: token is expired by 2h30m0s in Gin
This error occurs when a JWT token's expiration claim is past the current server time, or when the token signing key is mismatched between token creation and validation. Fix it by implementing proper token refresh logic, validating the signing method, and returning clear 401 responses with instructions for the client to obtain a new token.
Reading the Stack Trace
Here's what each line means:
- main.JWTAuthMiddleware.func1(0x14000226000) /app/middleware/jwt.go:28 +0x2d8: The JWT middleware at line 28 attempts to parse the token and encounters the expiration validation failure.
- github.com/golang-jwt/jwt/v5.(*Parser).Parse(0x14000118300, {0x14000116420, 0x120}, 0x14000226060): The JWT parser validates the token's claims including the 'exp' field, finding it expired.
- github.com/golang-jwt/jwt/v5.(*Validator).Validate(0x140001a8000, 0x14000196040): The validator checks the expiration timestamp against the current time and returns the expiry error.
Common Causes
1. Token expired with no refresh mechanism
The JWT has a short expiry and the client has no way to refresh it, forcing the user to log in again.
func JWTAuthMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
tokenStr := c.GetHeader("Authorization")
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
c.AbortWithStatus(401) // no details, no refresh guidance
return
}
c.Set("user", token.Claims)
c.Next()
}
}
2. Signing method not validated
The parser does not verify the signing algorithm, allowing an attacker to use alg:none to forge tokens.
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil // does not check t.Method
})
3. Wrong secret key between services
The token issuer and validator use different secret keys, causing every token to fail validation.
// Auth service uses SECRET_A
// API service uses SECRET_B
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
return []byte(os.Getenv("JWT_SECRET")), nil // different env var values
})
The Fix
Validate the Bearer prefix, verify the signing method is HMAC to prevent algorithm switching attacks, distinguish expired tokens from invalid ones, and return structured error responses with guidance on how to refresh the token.
func JWTAuthMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
tokenStr := c.GetHeader("Authorization")
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
return []byte(secret), nil
})
if err != nil {
c.AbortWithStatus(401)
return
}
c.Set("user", token.Claims)
c.Next()
}
}
func JWTAuthMiddleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
return
}
tokenStr := strings.TrimPrefix(authHeader, "Bearer ")
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "token_expired",
"message": "Token has expired. Please refresh your token at /auth/refresh.",
})
return
}
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid claims"})
return
}
c.Set("userID", claims["sub"])
c.Next()
}
}
Testing the Fix
package middleware_test
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/stretchr/testify/assert"
)
func makeToken(secret string, exp time.Time) string {
claims := jwt.MapClaims{"sub": "user123", "exp": jwt.NewNumericDate(exp)}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
s, _ := token.SignedString([]byte(secret))
return s
}
func TestJWT_ValidToken(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(JWTAuthMiddleware("secret"))
r.GET("/test", func(c *gin.Context) { c.Status(200) })
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("Authorization", "Bearer "+makeToken("secret", time.Now().Add(time.Hour)))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code)
}
func TestJWT_ExpiredToken(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(JWTAuthMiddleware("secret"))
r.GET("/test", func(c *gin.Context) { c.Status(200) })
req := httptest.NewRequest(http.MethodGet, "/test", nil)
req.Header.Set("Authorization", "Bearer "+makeToken("secret", time.Now().Add(-time.Hour)))
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
assert.Contains(t, w.Body.String(), "token_expired")
}
func TestJWT_MissingHeader(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(JWTAuthMiddleware("secret"))
r.GET("/test", func(c *gin.Context) { c.Status(200) })
req := httptest.NewRequest(http.MethodGet, "/test", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
assert.Equal(t, http.StatusUnauthorized, w.Code)
}
Run your tests:
go test ./middleware/... -v
Pushing Through CI/CD
git checkout -b fix/gin-jwt-auth-error,git add middleware/jwt.go middleware/jwt_test.go,git commit -m "fix: validate JWT signing method and handle expired tokens gracefully",git push origin fix/gin-jwt-auth-error
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.22'
- run: go mod download
- run: go vet ./...
- run: go test ./... -race -coverprofile=coverage.out
- run: go build ./...
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
go get github.com/bugstack/sdk
Step 2: Initialize
import "github.com/bugstack/sdk"
func init() {
bugstack.Init(os.Getenv("BUGSTACK_API_KEY"))
}
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run go test ./... locally to confirm the JWT middleware works correctly.
- Open a pull request with the JWT auth changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify the deployment in staging before promoting to production.
Frequently Asked Questions
BugStack runs the fix through your test suite, generates tests for expired, forged, and malformed tokens, and validates that all auth endpoints return correct status codes before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
15-30 minutes is a common choice for access tokens. Use refresh tokens (valid for days/weeks) stored securely to issue new access tokens without requiring re-login.
HMAC (HS256) is simpler for single-service setups. RSA (RS256) is better for microservices where only the auth service has the private key and others verify with the public key.