Baike.dev
All toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

gin-jwt

> 编程语言
Open source

JWT Middleware for Gin framework

3.0K stars0 likes0 views
WebsiteGitHub

About

JWT Middleware for Gin framework

Gin JWT Middleware

English | 繁體中文 | 简体中文 A powerful and flexible JWT authentication middleware for the Gin web framework, built on top of golang-jwt/jwt. Easily add login, token refresh, and authorization to your Gin applications.


Table of Contents

  • Gin JWT Middleware
    • Table of Contents
    • Features
    • Security Notice
      • Critical Security Requirements
      • ️ Production Security Checklist
      • OAuth 2.0 Security Standards
      • Secure Configuration Example
    • Installation
    • Quick Start Example
    • Complete Examples
      • Basic Authentication
      • OAuth SSO Integration
      • Token Generator
      • ️ Redis Store
      • ️ Authorization
    • Configuration
    • JWT Parsing Options
      • Clock Skew Tolerance (Leeway)
        • When to Use Leeway
        • Configuration Example
        • How Leeway Works
      • Other Parsing Options
        • JSON Number Handling
        • Required Claims Validation
        • Combining Multiple Options
    • Supporting Multiple JWT Providers
      • Use Cases
      • Solution: Dynamic Key Function
        • Why This Works
      • Implementation Strategy
        • Step 1: Create a Unified Middleware
        • Step 2: Helper Functions
        • Step 3: Route Setup
      • Complete Azure AD Integration Example
      • Alternative Approach: Custom Wrapper Middleware
      • Key Considerations
      • Testing Multi-Provider Setup
      • Common Issues and Solutions
      • Additional Resources
    • Token Generator (Direct Token Creation)
      • Basic Usage
      • Token Structure
      • Refresh Token Management
    • Redis Store Configuration
      • Redis Features
      • Redis Usage Methods
        • Using Functional Options Pattern (Recommended)
        • Available Options
      • Configuration Options
        • RedisConfig
      • Fallback Behavior
      • Example with Redis
    • Demo
      • Login
      • Refresh Token
      • Hello World
      • Authorization Example
    • Understanding the Authorizer
      • How Authorizer Works
      • Authorizer Function Signature
      • Basic Usage Examples
        • Example 1: Role-Based Authorization
        • Example 2: Path-Based Authorization
        • Example 3: Method and Path Based Authorization
      • Setting Up Different Authorization for Different Routes
        • Method 1: Multiple Middleware Instances
        • Method 2: Single Authorizer with Path Logic
      • Advanced Authorization Patterns
        • Using Claims for Fine-Grained Control
      • Common Patterns and Best Practices
      • Complete Example
      • Logout
    • Cookie Token
      • Refresh Token Cookie Support
      • Login request flow (using the LoginHandler)
      • Subsequent requests on endpoints requiring jwt token (using MiddlewareFunc)
      • Logout Request flow (using LogoutHandler)
      • Refresh Request flow (using RefreshHandler)
      • Failures with logging in, bad tokens, or lacking privileges

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

…

Installation

Requires Go 1.24+

go get -u github.com/appleboy/gin-jwt/v3
import "github.com/appleboy/gin-jwt/v3"

Quick Start Example

Please see the example file and you can use ExtractClaims to fetch user data.

…

Complete Examples

This repository provides several complete example implementations demonstrating different use cases:

Basic Authentication

The basic example showing fundamental JWT authentication with login, protected routes, and token validation.

OAuth SSO Integration

OAuth 2.0 Single Sign-On example supporting multiple identity providers (Google, GitHub):

  • OAuth 2.0 Authorization Code Flow
  • CSRF protection with state tokens
  • Dual authentication support: httpOnly cookies + Authorization headers
  • Secure token delivery for both browser and mobile apps
  • Interactive demo page included

Token Generator

Direct token generation without HTTP middleware, perfect for:

  • Programmatic authentication
  • Service-to-service communication
  • Testing authenticated endpoints
  • Custom authentication flows

️ Redis Store

Demonstrates Redis integration for refresh token storage with:

  • Client-side caching for improved performance
  • Automatic fallback to in-memory store
  • Production-ready configuration examples

️ Authorization

Advanced authorization patterns including:

  • Role-based access control
  • Path-based authorization
  • Multiple middleware instances
  • Fine-grained permission control

Configuration

The GinJWTMiddleware struct provides the following configuration options:

Option Type Required Default Description
Realm string No "gin jwt" Realm name to display to the user.
SigningAlgorithm string No "HS256" Signing algorithm (HS256, HS384, HS512, RS256, RS384, RS512).
Key []byte Yes - Secret key used for signing.
Timeout time.Duration No time.Hour Duration that a jwt token is valid.
MaxRefresh time.Duration No 0 Duration that a refresh token is valid.
Authenticator func(c *gin.Context) (any, error) Yes - Callback to authenticate the user. Returns user data.
Authorizer func(c *gin.Context, data any) bool No true Callback to authorize the authenticated user.
PayloadFunc func(data any) jwt.MapClaims No - Callback to add additional payload data to the token.
Unauthorized func(c *gin.Context, code int, message string) No - Callback for unauthorized requests.
LoginResponse func(c *gin.Context, token *core.Token) No - Callback for successful login response.
LogoutResponse func(c *gin.Context) No - Callback for successful logout response.

GitHub Issues· 0 open

View all on GitHub

No open issues yet, or sync has not completed.

> Tags

Gogingin-gwtjwt-middleware

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言