JWT Middleware for Gin framework
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.
⚠️ 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
RS256algorithm- Storage: Store secrets in environment variables, never hardcode in source code
- Vulnerability: Weak secrets are vulnerable to brute-force attacks (jwt-cracker)
SecureCookie, CookieHTTPOnly, and appropriate SameSite settingsThis library follows RFC 6749 OAuth 2.0 security standards:
…
Requires Go 1.24+
go get -u github.com/appleboy/gin-jwt/v3
import "github.com/appleboy/gin-jwt/v3"
Please see the example file and you can use ExtractClaims to fetch user data.
…
This repository provides several complete example implementations demonstrating different use cases:
The basic example showing fundamental JWT authentication with login, protected routes, and token validation.
OAuth 2.0 Single Sign-On example supporting multiple identity providers (Google, GitHub):
Direct token generation without HTTP middleware, perfect for:
Demonstrates Redis integration for refresh token storage with:
Advanced authorization patterns including:
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. |
No open issues yet, or sync has not completed.