Fix JWTError: code=401, message=missing or malformed jwt, internal=token contains an invalid number of segments in Echo
This error occurs when Echo's JWT middleware receives a token that is not a valid three-segment JWT string, typically because the Authorization header is missing the Bearer prefix or the token is truncated. Fix it by configuring the JWT middleware with proper token lookup, error handling, and a custom error response.
Reading the Stack Trace
Here's what each line means:
- github.com/labstack/echo-jwt/v4.(*jwtExtractor).extractToken({0x14000226000}): The JWT token extractor cannot find a valid token in the request, or the token string doesn't have the expected three-segment format.
- github.com/labstack/echo-jwt/v4.JWT.func1.1({0x1029e4f80, 0x14000226000}): The Echo JWT middleware processes the request and returns a 401 because token extraction failed.
- github.com/labstack/echo/v4.(*Echo).ServeHTTP(0x14000128680, {0x1029e4f80, 0x140001c40e0}, 0x140002b4000): Echo dispatches the request through the middleware chain where the JWT check occurs.
Common Causes
1. Missing Bearer prefix in Authorization header
The client sends the raw JWT token without the 'Bearer ' prefix that the middleware expects.
// Client sends: Authorization: eyJhbGciOi...
// Middleware expects: Authorization: Bearer eyJhbGciOi...
2. Default error handler leaks internal details
The default JWT error handler returns the internal error message which may reveal implementation details.
e.Use(echojwt.WithConfig(echojwt.Config{
SigningKey: []byte(secret),
// No custom ErrorHandler — returns raw jwt parse errors
}))
3. Token lookup not configured for cookie auth
The application stores the JWT in a cookie but the middleware looks in the Authorization header by default.
// Token stored in cookie "token"
e.Use(echojwt.WithConfig(echojwt.Config{
SigningKey: []byte(secret),
// Default TokenLookup is "header:Authorization"
// Should be "cookie:token"
}))
The Fix
Explicitly configure TokenLookup with the Bearer prefix scheme. Add a custom ErrorHandler that returns a clean JSON error response without leaking internal JWT parsing details to the client.
e.Use(echojwt.WithConfig(echojwt.Config{
SigningKey: []byte(os.Getenv("JWT_SECRET")),
}))
e.Use(echojwt.WithConfig(echojwt.Config{
SigningKey: []byte(os.Getenv("JWT_SECRET")),
TokenLookup: "header:Authorization:Bearer ",
ErrorHandler: func(c echo.Context, err error) error {
return c.JSON(http.StatusUnauthorized, map[string]string{
"error": "unauthorized",
"message": "Invalid or missing authentication token.",
})
},
ContinueOnIgnoredError: false,
}))
Testing the Fix
package main_test
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/golang-jwt/jwt/v5"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
)
func TestJWT_ValidToken(t *testing.T) {
e := setupEchoWithJWT("test-secret")
token := createTestToken("test-secret", time.Now().Add(time.Hour))
req := httptest.NewRequest(http.MethodGet, "/api/profile", nil)
req.Header.Set("Authorization", "Bearer "+token)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusOK, rec.Code)
}
func TestJWT_MissingToken(t *testing.T) {
e := setupEchoWithJWT("test-secret")
req := httptest.NewRequest(http.MethodGet, "/api/profile", nil)
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
assert.Contains(t, rec.Body.String(), "unauthorized")
}
func TestJWT_MalformedToken(t *testing.T) {
e := setupEchoWithJWT("test-secret")
req := httptest.NewRequest(http.MethodGet, "/api/profile", nil)
req.Header.Set("Authorization", "Bearer not.a.valid.token")
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
assert.Equal(t, http.StatusUnauthorized, rec.Code)
}
Run your tests:
go test ./... -v
Pushing Through CI/CD
git checkout -b fix/echo-jwt-error,git add main.go middleware/jwt.go,git commit -m "fix: configure JWT middleware with custom error handler and token lookup",git push origin fix/echo-jwt-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 JWT auth works.
- Open a pull request with the JWT middleware configuration.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify authentication in staging.
Frequently Asked Questions
BugStack runs the fix through your test suite, generates tests with expired, malformed, and missing tokens, and validates that the error responses do not leak internal details 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.
After the JWT middleware runs, use c.Get("user").(*jwt.Token) to get the parsed token, then access claims with token.Claims.(jwt.MapClaims) or use a custom claims struct.
Yes. Apply the JWT middleware to a group instead of globally. Public routes go outside the group, protected routes go inside it.