jwt

package module
v3.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2025 License: MIT Imports: 15 Imported by: 0

README

Gin JWT Middleware

English | 繁體中文 | 简体中文

Run Tests GitHub tag GoDoc Go Report Card codecov Sourcegraph

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.


Table of Contents


Features

  • 🔒 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

Security Notice

🔒 Critical Security Requirements

⚠️ 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)
🛡️ Production Security Checklist
  • 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 appropriate SameSite settings
  • Environment Variables: Store sensitive configuration in environment variables
  • Input Validation: Validate all authentication inputs thoroughly
🔄 OAuth 2.0 Security Standards

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
💡 Secure Configuration Example
// ❌ 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
}

Installation

import "github.com/appleboy/gin-jwt/v3"

Quick Start Example

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.",
  })
}


Token Generator (Direct Token Creation)

The TokenGenerator functionality allows you to create JWT tokens directly without HTTP middleware, perfect for programmatic authentication, testing, and custom flows.

Basic Usage
package main

import (
    "context"
    "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())
    }

    // Create context for token operations
    ctx := context.Background()

    // Generate a complete token pair (access + refresh tokens)
    userData := "user123"
    tokenPair, err := authMiddleware.TokenGenerator(ctx, 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())
}
Token Structure

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
Refresh Token Management

Use TokenGeneratorWithRevocation to refresh tokens and automatically revoke old ones:

// Refresh with automatic revocation of old token
newTokenPair, err := authMiddleware.TokenGeneratorWithRevocation(ctx, 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.


Redis Store Configuration

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.

Redis Features
  • 🔄 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
Redis Usage Methods

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
)
Available Options
  • WithRedisAddr(addr string) - Sets Redis server address
  • WithRedisAuth(password string, db int) - Sets authentication and database
  • WithRedisCache(size int, ttl time.Duration) - Configures client-side cache
  • WithRedisPool(poolSize int, maxIdleTime, maxLifetime time.Duration) - Configures connection pool
  • WithRedisKeyPrefix(prefix string) - Sets key prefix for Redis keys
Configuration Options
RedisConfig
  • 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:")
Fallback Behavior

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.

Example with Redis

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)
    }
}

Demo

Run the example server:

go run _example/basic/server.go

Install httpie for easy API testing.

Login
http -v --json POST localhost:8000/login username=admin password=admin

Login screenshot

Refresh Token

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

Refresh screenshot

Hello World

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"
}
Authorization Example

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."
}

Understanding the Authorizer

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.

How Authorizer Works

The Authorizer is called automatically during the JWT middleware processing for any route that uses MiddlewareFunc(). Here's the execution flow:

  1. Token Validation: JWT middleware validates the token
  2. Identity Extraction: IdentityHandler extracts user identity from token claims
  3. Authorization Check: Authorizer determines if the user can access the resource
  4. Route Access: If authorized, request proceeds; otherwise, Unauthorized is called
Authorizer Function Signature
func(c *gin.Context, data any) bool
  • c *gin.Context: The Gin context containing request information
  • data any: User identity data returned by IdentityHandler
  • Returns bool: true for authorized access, false to deny access
Basic Usage Examples
Example 1: Role-Based Authorization
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
    }
}
Example 2: Path-Based Authorization
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
    }
}
Example 3: Method and Path Based Authorization
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
    }
}
Setting Up Different Authorization for Different Routes

To implement different authorization rules for different route groups, you can create multiple middleware instances or use path checking within a single Authorizer:

Method 1: Multiple Middleware Instances
// 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())
Method 2: Single Authorizer with Path Logic
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
    }
}
Advanced Authorization Patterns
Using Claims for Fine-Grained Control
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]
}
Common Patterns and Best Practices
  1. Always validate the data type: Check if the user data can be cast to your expected type
  2. Use claims for additional context: Access JWT claims using jwt.ExtractClaims(c)
  3. Consider the request context: Use c.Request.URL.Path, c.Request.Method, etc.
  4. Fail securely: Return false by default and explicitly allow access
  5. Log authorization failures: Add logging for debugging authorization issues
Complete Example

See the authorization example for a complete implementation showing different authorization scenarios.

Logout

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
Login request flow (using the LoginHandler)

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)

Subsequent requests on endpoints requiring jwt token (using MiddlewareFunc)

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).

Logout Request flow (using LogoutHandler)

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)

Refresh Request flow (using RefreshHandler)

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)

Failures with logging in, bad tokens, or lacking privileges

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.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingSecretKey indicates Secret key is required
	ErrMissingSecretKey = errors.New("secret key is required")

	// ErrForbidden when HTTP status 403 is given
	ErrForbidden = errors.New("you don't have permission to access this resource")

	// ErrMissingAuthenticatorFunc indicates Authenticator is required
	ErrMissingAuthenticatorFunc = errors.New("ginJWTMiddleware.Authenticator func is undefined")

	// ErrMissingLoginValues indicates a user tried to authenticate without username or password
	ErrMissingLoginValues = errors.New("missing Username or Password")

	// ErrFailedAuthentication indicates authentication failed, could be faulty username or password
	ErrFailedAuthentication = errors.New("incorrect Username or Password")

	// ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
	ErrFailedTokenCreation = errors.New("failed to create JWT Token")

	// ErrExpiredToken indicates JWT token has expired. Can't refresh.
	ErrExpiredToken = errors.New("token is expired") // in practice, this is generated from the jwt library not by us

	// ErrEmptyAuthHeader can be thrown if authing with a HTTP header, the Auth header needs to be set
	ErrEmptyAuthHeader = errors.New("auth header is empty")

	// ErrMissingExpField missing exp field in token
	ErrMissingExpField = errors.New("missing exp field")

	// ErrWrongFormatOfExp field must be float64 format
	ErrWrongFormatOfExp = errors.New("exp must be float64 format")

	// ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name
	ErrInvalidAuthHeader = errors.New("auth header is invalid")

	// ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
	ErrEmptyQueryToken = errors.New("query token is empty")

	// ErrEmptyCookieToken can be thrown if authing with a cookie, the token cookie is empty
	ErrEmptyCookieToken = errors.New("cookie token is empty")

	// ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
	ErrEmptyParamToken = errors.New("parameter token is empty")

	// ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512, RS256, RS384 or RS512
	ErrInvalidSigningAlgorithm = errors.New("invalid signing algorithm")

	// ErrNoPrivKeyFile indicates that the given private key is unreadable
	ErrNoPrivKeyFile = errors.New("private key file unreadable")

	// ErrNoPubKeyFile indicates that the given public key is unreadable
	ErrNoPubKeyFile = errors.New("public key file unreadable")

	// ErrInvalidPrivKey indicates that the given private key is invalid
	ErrInvalidPrivKey = errors.New("private key invalid")

	// ErrInvalidPubKey indicates the the given public key is invalid
	ErrInvalidPubKey = errors.New("public key invalid")

	// IdentityKey default identity key
	IdentityKey = "identity"

	// ErrInvalidRefreshToken indicates the refresh token is invalid or expired
	ErrInvalidRefreshToken = errors.New("invalid or expired refresh token")

	// ErrRefreshTokenNotFound indicates the refresh token was not found in storage
	ErrRefreshTokenNotFound = errors.New("refresh token not found")
)

Functions

func ExtractClaims

func ExtractClaims(c *gin.Context) jwt.MapClaims

ExtractClaims help to extract the JWT claims

func ExtractClaimsFromToken

func ExtractClaimsFromToken(token *jwt.Token) jwt.MapClaims

ExtractClaimsFromToken help to extract the JWT claims from token

func GetToken

func GetToken(c *gin.Context) string

GetToken help to get the JWT token string

Types

type GinJWTMiddleware

type GinJWTMiddleware struct {
	// Realm name to display to the user. Required.
	Realm string

	// signing algorithm - possible values are HS256, HS384, HS512, RS256, RS384 or RS512
	// Optional, default is HS256.
	SigningAlgorithm string

	// Secret key used for signing. Required.
	Key []byte

	// Callback to retrieve key used for signing. Setting KeyFunc will bypass
	// all other key settings
	KeyFunc func(token *jwt.Token) (any, error)

	// Duration that a jwt token is valid. Optional, defaults to one hour.
	Timeout time.Duration
	// Callback function that will override the default timeout duration.
	TimeoutFunc func(data any) time.Duration

	// This field allows clients to refresh their token until MaxRefresh has passed.
	// Note that clients can refresh their token in the last moment of MaxRefresh.
	// This means that the maximum validity timespan for a token is TokenTime + MaxRefresh.
	// Optional, defaults to 0 meaning not refreshable.
	MaxRefresh time.Duration

	// Callback function that should perform the authentication of the user based on login info.
	// Must return user data as user identifier, it will be stored in Claim Array. Required.
	// Check error (e) to determine the appropriate error message.
	Authenticator func(c *gin.Context) (any, error)

	// Callback function that should perform the authorization of the authenticated user. Called
	// only after an authentication success. Must return true on success, false on failure.
	// Optional, default to success.
	Authorizer func(c *gin.Context, data any) bool

	// Callback function that will be called during login.
	// Using this function it is possible to add additional payload data to the webtoken.
	// The data is then made available during requests via c.Get("JWT_PAYLOAD").
	// Note that the payload is not encrypted.
	// The attributes mentioned on jwt.io can't be used as keys for the map.
	// Optional, by default no additional data will be set.
	PayloadFunc func(data any) jwt.MapClaims

	// User can define own Unauthorized func.
	Unauthorized func(c *gin.Context, code int, message string)

	// User can define own LoginResponse func.
	LoginResponse func(c *gin.Context, token *core.Token)

	// User can define own LogoutResponse func.
	LogoutResponse func(c *gin.Context)

	// User can define own RefreshResponse func.
	RefreshResponse func(c *gin.Context, token *core.Token)

	// Set the identity handler function
	IdentityHandler func(*gin.Context) any

	// Set the identity key
	IdentityKey string

	// TokenLookup is a string in the form of "<source>:<name>" that is used
	// to extract token from the request.
	// Optional. Default value "header:Authorization".
	// Possible values:
	// - "header:<name>"
	// - "query:<name>"
	// - "cookie:<name>"
	TokenLookup string

	// TokenHeadName is a string in the header. Default value is "Bearer"
	TokenHeadName string

	// TimeFunc provides the current time. You can override it to use another time value. This is useful for testing or if your server uses a different time zone than your tokens.
	TimeFunc func() time.Time

	// HTTP Status messages for when something in the JWT middleware fails.
	// Check error (e) to determine the appropriate error message.
	HTTPStatusMessageFunc func(c *gin.Context, e error) string

	// Private key file for asymmetric algorithms
	PrivKeyFile string

	// Private Key bytes for asymmetric algorithms
	//
	// Note: PrivKeyFile takes precedence over PrivKeyBytes if both are set
	PrivKeyBytes []byte

	// Public key file for asymmetric algorithms
	PubKeyFile string

	// Private key passphrase
	PrivateKeyPassphrase string

	// Public key bytes for asymmetric algorithms.
	//
	// Note: PubKeyFile takes precedence over PubKeyBytes if both are set
	PubKeyBytes []byte

	// Optionally return the token as a cookie
	SendCookie bool

	// Duration that a cookie is valid. Optional, by default equals to Timeout value.
	CookieMaxAge time.Duration

	// Allow insecure cookies for development over http
	SecureCookie bool

	// Allow cookies to be accessed client side for development
	CookieHTTPOnly bool

	// Allow cookie domain change for development
	CookieDomain string

	// SendAuthorization allow return authorization header for every request
	SendAuthorization bool

	// Disable abort() of context.
	DisabledAbort bool

	// CookieName allow cookie name change for development
	CookieName string

	// CookieSameSite allow use http.SameSite cookie param
	CookieSameSite http.SameSite

	// ParseOptions allow to modify jwt's parser methods.
	// WithTimeFunc is always added to ensure the TimeFunc is propagated to the validator
	ParseOptions []jwt.ParserOption

	// Default value is "exp"
	ExpField string

	// RefreshTokenTimeout specifies how long refresh tokens are valid
	// Defaults to 30 days if not set
	RefreshTokenTimeout time.Duration

	// RefreshTokenStore interface for storing and retrieving refresh tokens
	// If nil, an in-memory store will be used
	RefreshTokenStore core.TokenStore

	// RefreshTokenLength specifies the byte length of refresh tokens (default: 32)
	RefreshTokenLength int

	// UseRedisStore indicates whether to use Redis store instead of in-memory store
	// When true, will attempt to connect to Redis using RedisConfig
	UseRedisStore bool

	// RedisConfig configuration for Redis store when UseRedisStore is true
	// If nil when UseRedisStore is true, will use default Redis configuration
	RedisConfig *store.RedisConfig
	// contains filtered or unexported fields
}

GinJWTMiddleware provides a Json-Web-Token authentication implementation. On failure, a 401 HTTP response is returned. On success, the wrapped middleware is called, and the userID is made available as c.Get("userID").(string). Users can get a token by posting a json request to LoginHandler. The token then needs to be passed in the Authentication header. Example: Authorization:Bearer XXX_TOKEN_XXX

func New

New creates and initializes a new GinJWTMiddleware instance

func (*GinJWTMiddleware) CheckIfTokenExpire

func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error)

CheckIfTokenExpire check if token expire

func (*GinJWTMiddleware) ClearSensitiveData

func (mw *GinJWTMiddleware) ClearSensitiveData()

ClearSensitiveData clears sensitive data from memory

func (*GinJWTMiddleware) EnableRedisStore

func (mw *GinJWTMiddleware) EnableRedisStore(opts ...RedisOption) *GinJWTMiddleware

EnableRedisStore enables Redis store with optional configuration

func (*GinJWTMiddleware) GetClaimsFromJWT

func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (jwt.MapClaims, error)

GetClaimsFromJWT get claims from JWT token

func (*GinJWTMiddleware) LoginHandler

func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context)

LoginHandler can be used by clients to get a jwt token. Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}. Reply will be of the form {"token": "TOKEN"}.

func (*GinJWTMiddleware) LogoutHandler

func (mw *GinJWTMiddleware) LogoutHandler(c *gin.Context)

LogoutHandler can be used by clients to remove the jwt cookie and revoke refresh token

func (*GinJWTMiddleware) MiddlewareFunc

func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc

MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface.

func (*GinJWTMiddleware) MiddlewareInit

func (mw *GinJWTMiddleware) MiddlewareInit() error

MiddlewareInit initializes JWT middleware configuration with default values

func (*GinJWTMiddleware) ParseToken

func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error)

ParseToken parse jwt token from gin context

func (*GinJWTMiddleware) ParseTokenString

func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error)

ParseTokenString parse jwt token string

func (*GinJWTMiddleware) RefreshHandler

func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context)

RefreshHandler can be used to refresh a token using RFC 6749 compliant refresh tokens. This handler expects a refresh_token parameter and returns a new access token and refresh token. Reply will be of the form {"access_token": "TOKEN", "refresh_token": "REFRESH_TOKEN"}.

func (*GinJWTMiddleware) SetCookie

func (mw *GinJWTMiddleware) SetCookie(c *gin.Context, token string)

SetCookie help to set the token in the cookie

func (*GinJWTMiddleware) TokenGenerator

func (mw *GinJWTMiddleware) TokenGenerator(ctx context.Context, data any) (*core.Token, error)

TokenGenerator generates a complete token pair (access + refresh) with RFC 6749 compliance

func (*GinJWTMiddleware) TokenGeneratorWithRevocation

func (mw *GinJWTMiddleware) TokenGeneratorWithRevocation(ctx context.Context, data any, oldRefreshToken string) (*core.Token, error)

TokenGeneratorWithRevocation generates a new token pair and revokes the old refresh token

type RedisOption

type RedisOption func(*store.RedisConfig)

RedisOption defines a function type for configuring Redis store

func WithRedisAddr

func WithRedisAddr(addr string) RedisOption

WithRedisAddr sets the Redis server address

func WithRedisAuth

func WithRedisAuth(password string, db int) RedisOption

WithRedisAuth sets Redis authentication

func WithRedisCache

func WithRedisCache(size int, ttl time.Duration) RedisOption

WithRedisCache configures client-side cache

func WithRedisKeyPrefix

func WithRedisKeyPrefix(prefix string) RedisOption

WithRedisKeyPrefix sets the key prefix

func WithRedisPool

func WithRedisPool(poolSize int, maxIdleTime, maxLifetime time.Duration) RedisOption

WithRedisPool configures connection pool

Directories

Path Synopsis
_example
redis_simple command
Package core provides core interfaces and types for gin-jwt
Package core provides core interfaces and types for gin-jwt
Package store provides implementations for refresh token storage
Package store provides implementations for refresh token storage

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL