Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you implement JWT authentication middleware in Go?
JWT (JSON Web Token) authentication middleware validates the token on every request, extracts claims, and attaches them to the request context for use by downstream handlers.
import "github.com/golang-jwt/jwt/v5"
type Claims struct {
UserID int `json:"user_id"`
Role string `json:"role"`
jwt.RegisteredClaims
}
type contextKey string
const claimsKey contextKey = "claims"
func jwtMiddleware(secret []byte) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Extract token from Authorization: Bearer
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
writeJSON(w, http.StatusUnauthorized,
map[string]string{"error": "missing bearer token"})
return
}
tokenString := strings.TrimPrefix(auth, "Bearer ")
// Parse and validate
var claims Claims
token, err := jwt.ParseWithClaims(tokenString, &claims,
func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v",
token.Header["alg"])
}
return secret, nil
})
if err != nil || !token.Valid {
writeJSON(w, http.StatusUnauthorized,
map[string]string{"error": "invalid or expired token"})
return
}
// Attach claims to context
ctx := context.WithValue(r.Context(), claimsKey, &claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// Helper to extract claims in handlers
func claimsFromCtx(ctx context.Context) (*Claims, bool) {
c, ok := ctx.Value(claimsKey).(*Claims)
return c, ok
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
