Gin JWT Claims Middleware
Extract and verify JWT claims in Gin middleware, checking issuer and role before handlers, with claims injected into context.
Code
package main
import (
"errors"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
var errInvalidToken = errors.New("invalid token")
type AppClaims struct {
UserID string `json:"uid"`
Role string `json:"role"`
jwt.RegisteredClaims
}
func authMiddleware(secret string, allowedRoles ...string) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
return
}
token, err := jwt.ParseWithClaims(
strings.TrimPrefix(header, "Bearer "),
&AppClaims{},
func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, errors.New("unexpected signing method")
}
return []byte(secret), nil
},
jwt.WithIssuer("auth.example.com"),
jwt.WithExpirationRequired(),
)
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": errInvalidToken.Error()})
return
}
claims := token.Claims.(*AppClaims)
for _, role := range allowedRoles {
if claims.Role == role {
c.Set("claims", claims)
c.Next()
return
}
}
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "role not permitted"})
}
}
func main() {
r := gin.New()
r.GET("/admin/stats", authMiddleware("secret", "admin"), func(c *gin.Context) {
claims := c.MustGet("claims").(*AppClaims)
c.JSON(http.StatusOK, gin.H{"for": claims.UserID, "generated": time.Now().Unix()})
})
r.Run(":8080")
}How the snippet works
Structurally, expect the functions authMiddleware and main and nothing else.
for _, role := range allowedRoles drives the per-item pass across the whole data set. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.
Points of care
- Plan for an install step:
github.com/gin-gonic/ginandgithub.com/golang-jwt/jwt/v5are a real dependency, resolved by the package manager. erroris part of the return tuple, so every caller decides what failure means.
Applying it
Signature: func authMiddleware(secret string, allowedRoles ...string) gin.HandlerFunc
Execute the file and main walks through authMiddleware, in that order.
Statements that carry the weight
return nil, errors.New("unexpected signing method")
for _, role := range allowedRoles {
if claims.Role == role {
c.Set("claims", claims)
c.Next()
return
}
}
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": errInvalidToken.Error()})
return
}
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- How do errors reach the caller?
- As returned `error` values, checked at its call site — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
- Which packages must be installed first?
- Yes. The imports resolve to `github.com/gin-gonic/gin` and `github.com/golang-jwt/jwt/v5`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.