A powerful and flexible JWT authentication middleware for the Gin web framework, built on top of jwt-go. Easily add login, token refresh, and authorization to your Gin applications.
- Gin JWT Middleware
- Table of Contents
- Features
- Security Notice
- Installation
- Quick Start Example
- Token Generator (Direct Token Creation)
- Redis Store Configuration
- Demo
- Understanding the Authorizer
- Cookie Token
- 🔒 Simple JWT authentication for Gin
- 🔁 Built-in login, refresh, and logout handlers
- 🛡️ Customizable authentication, authorization, and claims
- 🍪 Cookie and header token support
- 📝 Easy integration and clear API
- 🔐 RFC 6749 compliant refresh tokens (OAuth 2.0 standard)
- 🗄️ Pluggable refresh token storage (in-memory, Redis with client-side caching)
- 🏭 Direct token generation without HTTP middleware
- 📦 Structured Token type with metadata
⚠️ JWT Secret Security
- Minimum Requirements: Use secrets of at least 256 bits (32 bytes) in length
- Never use: Simple passwords, dictionary words, or predictable patterns
- Recommended: Generate cryptographically secure random secrets or use
RS256
algorithm- Storage: Store secrets in environment variables, never hardcode in source code
- Vulnerability: Weak secrets are vulnerable to brute-force attacks (jwt-cracker)
- ✅ HTTPS Only: Always use HTTPS in production environments
- ✅ Strong Secrets: Minimum 256-bit randomly generated secrets
- ✅ Token Expiry: Set appropriate timeout values (recommended: 15-60 minutes for access tokens)
- ✅ Secure Cookies: Enable
SecureCookie
,CookieHTTPOnly
, and appropriateSameSite
settings - ✅ Environment Variables: Store sensitive configuration in environment variables
- ✅ Input Validation: Validate all authentication inputs thoroughly
This library follows RFC 6749 OAuth 2.0 security standards:
- Separate Tokens: Uses distinct opaque refresh tokens (not JWT) for enhanced security
- Server-Side Storage: Refresh tokens are stored and validated server-side
- Token Rotation: Refresh tokens are automatically rotated on each use
- Improved Security: Prevents JWT refresh token vulnerabilities and replay attacks
// ❌ BAD: Weak secret, insecure settings
authMiddleware := &jwt.GinJWTMiddleware{
Key: []byte("weak"), // Too short!
Timeout: time.Hour * 24, // Too long!
SecureCookie: false, // Insecure in production!
}
// ✅ GOOD: Strong security configuration
authMiddleware := &jwt.GinJWTMiddleware{
Key: []byte(os.Getenv("JWT_SECRET")), // From environment
Timeout: time.Minute * 15, // Short-lived access tokens
MaxRefresh: time.Hour * 24 * 7, // 1 week refresh validity
SecureCookie: true, // HTTPS only
CookieHTTPOnly: true, // Prevent XSS
CookieSameSite: http.SameSiteStrictMode, // CSRF protection
SendCookie: true, // Enable secure cookies
}
import "github.com/appleboy/gin-jwt/v3"
Please see the example file and you can use ExtractClaims
to fetch user data.
package main
import (
"log"
"net/http"
"os"
"time"
jwt "github.com/appleboy/gin-jwt/v3"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
type login struct {
Username string `form:"username" json:"username" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
var (
identityKey = "id"
port string
)
// User demo
type User struct {
UserName string
FirstName string
LastName string
}
func init() {
port = os.Getenv("PORT")
if port == "" {
port = "8000"
}
}
func main() {
engine := gin.Default()
// the jwt middleware
authMiddleware, err := jwt.New(initParams())
if err != nil {
log.Fatal("JWT Error:" + err.Error())
}
// initialize middleware
errInit := authMiddleware.MiddlewareInit()
if errInit != nil {
log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
}
// register route
registerRoute(engine, authMiddleware)
// start http server
if err = http.ListenAndServe(":"+port, engine); err != nil {
log.Fatal(err)
}
}
func registerRoute(r *gin.Engine, handle *jwt.GinJWTMiddleware) {
// Public routes
r.POST("/login", handle.LoginHandler)
r.POST("/refresh", handle.RefreshHandler) // RFC 6749 compliant refresh endpoint
// Protected routes
auth := r.Group("/auth", handle.MiddlewareFunc())
auth.GET("/hello", helloHandler)
auth.POST("/logout", handle.LogoutHandler) // Logout with refresh token revocation
}
func initParams() *jwt.GinJWTMiddleware {
return &jwt.GinJWTMiddleware{
Realm: "test zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour,
IdentityKey: identityKey,
PayloadFunc: payloadFunc(),
IdentityHandler: identityHandler(),
Authenticator: authenticator(),
Authorizer: authorizator(),
Unauthorized: unauthorized(),
TokenLookup: "header: Authorization, query: token, cookie: jwt",
// TokenLookup: "query:token",
// TokenLookup: "cookie:token",
TokenHeadName: "Bearer",
TimeFunc: time.Now,
}
}
func payloadFunc() func(data any) jwt.MapClaims {
return func(data any) jwt.MapClaims {
if v, ok := data.(*User); ok {
return jwt.MapClaims{
identityKey: v.UserName,
}
}
return jwt.MapClaims{}
}
}
func identityHandler() func(c *gin.Context) any {
return func(c *gin.Context) any {
claims := jwt.ExtractClaims(c)
return &User{
UserName: claims[identityKey].(string),
}
}
}
func authenticator() func(c *gin.Context) (any, error) {
return func(c *gin.Context) (any, error) {
var loginVals login
if err := c.ShouldBind(&loginVals); err != nil {
return "", jwt.ErrMissingLoginValues
}
userID := loginVals.Username
password := loginVals.Password
if (userID == "admin" && password == "admin") || (userID == "test" && password == "test") {
return &User{
UserName: userID,
LastName: "Bo-Yi",
FirstName: "Wu",
}, nil
}
return nil, jwt.ErrFailedAuthentication
}
}
func authorizator() func(data any, c *gin.Context) bool {
return func(data any, c *gin.Context) bool {
if v, ok := data.(*User); ok && v.UserName == "admin" {
return true
}
return false
}
}
func unauthorized() func(c *gin.Context, code int, message string) {
return func(c *gin.Context, code int, message string) {
c.JSON(code, gin.H{
"code": code,
"message": message,
})
}
}
func handleNoRoute() func(c *gin.Context) {
return func(c *gin.Context) {
c.JSON(404, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"})
}
}
func helloHandler(c *gin.Context) {
claims := jwt.ExtractClaims(c)
user, _ := c.Get(identityKey)
c.JSON(200, gin.H{
"userID": claims[identityKey],
"userName": user.(*User).UserName,
"text": "Hello World.",
})
}
The TokenGenerator
functionality allows you to create JWT tokens directly without HTTP middleware, perfect for programmatic authentication, testing, and custom flows.
package main
import (
"fmt"
"log"
"time"
jwt "github.com/appleboy/gin-jwt/v3"
gojwt "github.com/golang-jwt/jwt/v5"
)
func main() {
// Initialize the middleware
authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
Realm: "example zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
PayloadFunc: func(data any) gojwt.MapClaims {
return gojwt.MapClaims{
"user_id": data,
}
},
})
if err != nil {
log.Fatal("JWT Error:" + err.Error())
}
// Generate a complete token pair (access + refresh tokens)
userData := "user123"
tokenPair, err := authMiddleware.TokenGenerator(userData)
if err != nil {
log.Fatal("Failed to generate token pair:", err)
}
fmt.Printf("Access Token: %s\n", tokenPair.AccessToken)
fmt.Printf("Refresh Token: %s\n", tokenPair.RefreshToken)
fmt.Printf("Expires In: %d seconds\n", tokenPair.ExpiresIn())
}
The TokenGenerator
method returns a structured core.Token
:
type Token struct {
AccessToken string `json:"access_token"` // JWT access token
TokenType string `json:"token_type"` // Always "Bearer"
RefreshToken string `json:"refresh_token"` // Opaque refresh token
ExpiresAt int64 `json:"expires_at"` // Unix timestamp
CreatedAt int64 `json:"created_at"` // Unix timestamp
}
// Helper method
func (t *Token) ExpiresIn() int64 // Returns seconds until expiry
Use TokenGeneratorWithRevocation
to refresh tokens and automatically revoke old ones:
// Refresh with automatic revocation of old token
newTokenPair, err := authMiddleware.TokenGeneratorWithRevocation(userData, oldRefreshToken)
if err != nil {
log.Fatal("Failed to refresh token:", err)
}
// Old refresh token is now invalid
fmt.Printf("New Access Token: %s\n", newTokenPair.AccessToken)
fmt.Printf("New Refresh Token: %s\n", newTokenPair.RefreshToken)
Use Cases:
- 🔧 Programmatic Authentication: Service-to-service communication
- 🧪 Testing: Generate tokens for testing authenticated endpoints
- 📝 Registration Flow: Issue tokens immediately after user signup
- ⚙️ Background Jobs: Create tokens for automated processes
- 🎛️ Custom Auth Flows: Build custom authentication logic
See the complete example for more details.
This library supports Redis as a backend for refresh token storage, with built-in client-side caching for improved performance. Redis store provides better scalability and persistence compared to the default in-memory store.
- 🔄 Client-side Caching: Built-in Redis client-side caching for improved performance
- 🚀 Automatic Fallback: Falls back to in-memory store if Redis connection fails
- ⚙️ Easy Configuration: Simple methods to configure Redis store
- 🔧 Method Chaining: Fluent API for convenient configuration
- 📦 Factory Pattern: Support for both Redis and memory stores
The Redis configuration now uses a functional options pattern for cleaner and more flexible configuration:
// Method 1: Enable Redis with default configuration
middleware := &jwt.GinJWTMiddleware{
// ... other configuration
}.EnableRedisStore()
// Method 2: Enable Redis with custom address
middleware := &jwt.GinJWTMiddleware{
// ... other configuration
}.EnableRedisStore(
jwt.WithRedisAddr("redis.example.com:6379"),
)
// Method 3: Enable Redis with authentication
middleware := &jwt.GinJWTMiddleware{
// ... other configuration
}.EnableRedisStore(
jwt.WithRedisAddr("redis.example.com:6379"),
jwt.WithRedisAuth("password", 0),
)
// Method 4: Full configuration with all options
middleware := &jwt.GinJWTMiddleware{
// ... other configuration
}.EnableRedisStore(
jwt.WithRedisAddr("redis.example.com:6379"),
jwt.WithRedisAuth("password", 1),
jwt.WithRedisCache(128*1024*1024, time.Minute), // 128MB cache, 1min TTL
jwt.WithRedisPool(20, time.Hour, 2*time.Hour), // Pool config
jwt.WithRedisKeyPrefix("myapp:jwt:"), // Key prefix
)
WithRedisAddr(addr string)
- Sets Redis server addressWithRedisAuth(password string, db int)
- Sets authentication and databaseWithRedisCache(size int, ttl time.Duration)
- Configures client-side cacheWithRedisPool(poolSize int, maxIdleTime, maxLifetime time.Duration)
- Configures connection poolWithRedisKeyPrefix(prefix string)
- Sets key prefix for Redis keys
- Addr: Redis server address (default:
"localhost:6379"
) - Password: Redis password (default:
""
) - DB: Redis database number (default:
0
) - CacheSize: Client-side cache size in bytes (default:
128MB
) - CacheTTL: Client-side cache TTL (default:
1 minute
) - KeyPrefix: Prefix for all Redis keys (default:
"gin-jwt:"
)
If Redis connection fails during initialization:
- The middleware logs an error message
- Automatically falls back to in-memory store
- Application continues to function normally
This ensures high availability and prevents application failures due to Redis connectivity issues.
See the Redis example for a complete implementation.
package main
import (
"log"
"net/http"
"time"
jwt "github.com/appleboy/gin-jwt/v3"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
authMiddleware, err := jwt.New(&jwt.GinJWTMiddleware{
Realm: "example zone",
Key: []byte("secret key"),
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
IdentityKey: "id",
PayloadFunc: func(data any) jwt.MapClaims {
if v, ok := data.(map[string]any); ok {
return jwt.MapClaims{
"id": v["username"],
}
}
return jwt.MapClaims{}
},
Authenticator: func(c *gin.Context) (any, error) {
var loginVals struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.ShouldBind(&loginVals); err != nil {
return "", jwt.ErrMissingLoginValues
}
if loginVals.Username == "admin" && loginVals.Password == "admin" {
return map[string]any{
"username": loginVals.Username,
}, nil
}
return nil, jwt.ErrFailedAuthentication
},
}).EnableRedisStore( // Enable Redis with options
jwt.WithRedisAddr("localhost:6379"), // Redis server address
jwt.WithRedisCache(64*1024*1024, 30*time.Second), // 64MB cache, 30s TTL
)
if err != nil {
log.Fatal("JWT Error:" + err.Error())
}
errInit := authMiddleware.MiddlewareInit()
if errInit != nil {
log.Fatal("authMiddleware.MiddlewareInit() Error:" + errInit.Error())
}
r.POST("/login", authMiddleware.LoginHandler)
auth := r.Group("/auth")
auth.Use(authMiddleware.MiddlewareFunc())
{
auth.GET("/hello", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello World.",
})
})
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
}
if err := http.ListenAndServe(":8000", r); err != nil {
log.Fatal(err)
}
}
Run the example server:
go run _example/basic/server.go
Install httpie for easy API testing.
http -v --json POST localhost:8000/login username=admin password=admin
Using RFC 6749 compliant refresh tokens (default behavior):
# First login to get refresh token
http -v --json POST localhost:8000/login username=admin password=admin
# Use refresh token to get new access token (public endpoint)
http -v --form POST localhost:8000/refresh refresh_token=your_refresh_token_here
Login as admin
/admin
and call:
http -f GET localhost:8000/auth/hello "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"
Response:
{
"text": "Hello World.",
"userID": "admin"
}
Login as test
/test
and call:
http -f GET localhost:8000/auth/hello "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"
Response:
{
"code": 403,
"message": "You don't have permission to access."
}
The Authorizer
function is a crucial component for implementing role-based access control in your application. It determines whether an authenticated user has permission to access specific protected routes.
The Authorizer
is called automatically during the JWT middleware processing for any route that uses MiddlewareFunc()
. Here's the execution flow:
- Token Validation: JWT middleware validates the token
- Identity Extraction:
IdentityHandler
extracts user identity from token claims - Authorization Check:
Authorizer
determines if the user can access the resource - Route Access: If authorized, request proceeds; otherwise,
Unauthorized
is called
func(c *gin.Context, data any) bool
c *gin.Context
: The Gin context containing request informationdata any
: User identity data returned byIdentityHandler
- Returns
bool
:true
for authorized access,false
to deny access
func authorizeHandler() func(c *gin.Context, data any) bool {
return func(c *gin.Context, data any) bool {
if v, ok := data.(*User); ok && v.UserName == "admin" {
return true // Only admin users can access
}
return false
}
}
func authorizeHandler() func(c *gin.Context, data any) bool {
return func(c *gin.Context, data any) bool {
user, ok := data.(*User)
if !ok {
return false
}
path := c.Request.URL.Path
// Admin can access all routes
if user.Role == "admin" {
return true
}
// Regular users can only access /auth/profile and /auth/hello
allowedPaths := []string{"/auth/profile", "/auth/hello"}
for _, allowedPath := range allowedPaths {
if path == allowedPath {
return true
}
}
return false
}
}
func authorizeHandler() func(c *gin.Context, data any) bool {
return func(c *gin.Context, data any) bool {
user, ok := data.(*User)
if !ok {
return false
}
path := c.Request.URL.Path
method := c.Request.Method
// Admins have full access
if user.Role == "admin" {
return true
}
// Users can only GET their own profile
if path == "/auth/profile" && method == "GET" {
return true
}
// Users cannot modify or delete resources
if method == "POST" || method == "PUT" || method == "DELETE" {
return false
}
return true // Allow other GET requests
}
}
To implement different authorization rules for different route groups, you can create multiple middleware instances or use path checking within a single Authorizer:
// Admin-only middleware
adminMiddleware, _ := jwt.New(&jwt.GinJWTMiddleware{
// ... other config
Authorizer: func(c *gin.Context, data any) bool {
if user, ok := data.(*User); ok {
return user.Role == "admin"
}
return false
},
})
// Regular user middleware
userMiddleware, _ := jwt.New(&jwt.GinJWTMiddleware{
// ... other config
Authorizer: func(c *gin.Context, data any) bool {
if user, ok := data.(*User); ok {
return user.Role == "user" || user.Role == "admin"
}
return false
},
})
// Route setup
adminRoutes := r.Group("/admin", adminMiddleware.MiddlewareFunc())
userRoutes := r.Group("/user", userMiddleware.MiddlewareFunc())
func authorizeHandler() func(c *gin.Context, data any) bool {
return func(c *gin.Context, data any) bool {
user, ok := data.(*User)
if !ok {
return false
}
path := c.Request.URL.Path
// Admin routes - only admins allowed
if strings.HasPrefix(path, "/admin/") {
return user.Role == "admin"
}
// User routes - users and admins allowed
if strings.HasPrefix(path, "/user/") {
return user.Role == "user" || user.Role == "admin"
}
// Public authenticated routes - all authenticated users
return true
}
}
func authorizeHandler() func(c *gin.Context, data any) bool {
return func(c *gin.Context, data any) bool {
// Extract additional claims
claims := jwt.ExtractClaims(c)
// Get user permissions from claims
permissions, ok := claims["permissions"].([]interface{})
if !ok {
return false
}
// Check if user has required permission for this route
requiredPermission := getRequiredPermission(c.Request.URL.Path)
for _, perm := range permissions {
if perm.(string) == requiredPermission {
return true
}
}
return false
}
}
func getRequiredPermission(path string) string {
permissionMap := map[string]string{
"/auth/users": "read_users",
"/auth/reports": "read_reports",
"/auth/settings": "admin",
}
return permissionMap[path]
}
- Always validate the data type: Check if the user data can be cast to your expected type
- Use claims for additional context: Access JWT claims using
jwt.ExtractClaims(c)
- Consider the request context: Use
c.Request.URL.Path
,c.Request.Method
, etc. - Fail securely: Return
false
by default and explicitly allow access - Log authorization failures: Add logging for debugging authorization issues
See the authorization example for a complete implementation showing different authorization scenarios.
Login first, then call the logout endpoint with the JWT token:
# First login to get the JWT token
http -v --json POST localhost:8000/login username=admin password=admin
# Use the returned JWT token to logout (replace xxxxxxxxx with actual token)
http -f POST localhost:8000/auth/logout "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"
Response:
{
"code": 200,
"logged_out_user": "admin",
"message": "Successfully logged out",
"user_info": "admin"
}
The logout response demonstrates that JWT claims are now accessible during logout through jwt.ExtractClaims(c)
, allowing developers to access user information for logging, auditing, or cleanup purposes.
To set the JWT in a cookie, use these options (see MDN docs):
SendCookie: true,
SecureCookie: false, // for non-HTTPS dev environments
CookieHTTPOnly: true, // JS can't modify
CookieDomain: "localhost:8080",
CookieName: "token", // default jwt
TokenLookup: "cookie:token",
CookieSameSite: http.SameSiteDefaultMode, // SameSiteDefaultMode, SameSiteLaxMode, SameSiteStrictMode, SameSiteNoneMode
PROVIDED: LoginHandler
This is a provided function to be called on any login endpoint, which will trigger the flow described below.
REQUIRED: Authenticator
This function should verify the user credentials given the gin context (i.e. password matches hashed password for a given user email, and any other authentication logic). Then the authenticator should return a struct or map that contains the user data that will be embedded in the jwt token. This might be something like an account id, role, is_verified, etc. After having successfully authenticated, the data returned from the authenticator is passed in as a parameter into the PayloadFunc
, which is used to embed the user identifiers mentioned above into the jwt token. If an error is returned, the Unauthorized
function is used (explained below).
OPTIONAL: PayloadFunc
This function is called after having successfully authenticated (logged in). It should take whatever was returned from Authenticator
and convert it into MapClaims
(i.e. map[string]any). A typical use case of this function is for when Authenticator
returns a struct which holds the user identifiers, and that struct needs to be converted into a map. MapClaims
should include one element that is [IdentityKey
(default is "identity"): some_user_identity]. The elements of MapClaims
returned in PayloadFunc
will be embedded within the jwt token (as token claims). When users pass in their token on subsequent requests, you can get these claims back by using ExtractClaims
.
OPTIONAL: LoginResponse
After having successfully authenticated with Authenticator
, created the jwt token using the identifiers from map returned from PayloadFunc
, and set it as a cookie if SendCookie
is enabled, this function is called. It receives the complete token information (including access token, refresh token, expiry, etc.) as a structured core.Token
object. This function is used to handle any post-login logic and return the token response to the user.
Signature: func(c *gin.Context, token *core.Token)
PROVIDED: MiddlewareFunc
This is gin middleware that should be used within any endpoints that require the jwt token to be present. This middleware will parse the request headers for the token if it exists, and check that the jwt token is valid (not expired, correct signature). Then it will call IdentityHandler
followed by Authorizer
. If Authorizer
passes and all of the previous token validity checks passed, the middleware will continue the request. If any of these checks fail, the Unauthorized
function is used (explained below).
OPTIONAL: IdentityHandler
The default of this function is likely sufficient for your needs. The purpose of this function is to fetch the user identity from claims embedded within the jwt token, and pass this identity value to Authorizer
. This function assumes [IdentityKey
: some_user_identity] is one of the attributes embedded within the claims of the jwt token (determined by PayloadFunc
).
OPTIONAL: Authorizer
Given the user identity value (data
parameter) and the gin context, this function should check if the user is authorized to be reaching this endpoint (on the endpoints where the MiddlewareFunc
applies). This function should likely use ExtractClaims
to check if the user has the sufficient permissions to reach this endpoint, as opposed to hitting the database on every request. This function should return true if the user is authorized to continue through with the request, or false if they are not authorized (where Unauthorized
will be called).
PROVIDED: LogoutHandler
This is a provided function to be called on any logout endpoint, which will clear any cookies if SendCookie
is set, and then call LogoutResponse
.
OPTIONAL: LogoutResponse
This function is called after logout processing is complete. It should return the appropriate HTTP response to indicate logout success or failure. Since logout doesn't generate new tokens, this function only receives the gin context.
Signature: func(c *gin.Context)
PROVIDED: RefreshHandler
:
This is a provided function to be called on any refresh token endpoint. The handler expects a refresh_token
parameter (RFC 6749 compliant) and validates it against the server-side token store. If the refresh token is valid and not expired, the handler will create a new access token and refresh token, revoke the old refresh token, and pass the new tokens into RefreshResponse
. This follows OAuth 2.0 security best practices by rotating refresh tokens.
OPTIONAL: RefreshResponse
:
This function is called after successfully refreshing tokens. It receives the complete new token information as a structured core.Token
object and should return a JSON response containing the new access_token
, token_type
, expires_in
, and refresh_token
fields, following RFC 6749 token response format.
Signature: func(c *gin.Context, token *core.Token)
OPTIONAL Unauthorized
:
On any error logging in, authorizing the user, or when there was no token or a invalid token passed in with the request, the following will happen. The gin context will be aborted depending on DisabledAbort
, then HTTPStatusMessageFunc
is called which by default converts the error into a string. Finally the Unauthorized
function will be called. This function should likely return a JSON containing the http error code and error message to the user.