Documentation
¶
Overview ¶
Package jwt_auth provides an extendable interface for JWT authentication in a Gin-based API, leveraging the github.com/appleboy/gin-jwt middleware. It enables API developers to quickly set up stateless authentication mechanisms using JSON Web Tokens while offering hooks for customization
Core Capabilities:
- SetSecretKey initializes the JWT secret key used for signing tokens
- Dynamically generates middleware parameters via `GenerateParams` from configurable inputs
- Registers standard JWT routes (`/login`, `/refresh`, `/logout`) with optional prefixing
- Provides a reusable middleware handler function for protecting API routes
- Offers convenience methods for standardized unauthorized responses and fallback NoRoute handling
Usage:
To use the package:
// Step 1: Initialize JWT settings
err := jwt_auth.SetSecretKey(yourJwtSecret)
if err != nil {
log.Fatalf("JWT initialization failed: %v", err)
}
// Step 2: Generate middleware parameters (example parameters shown below)
middleware, err := jwt_auth.GenerateParams[MyUserStruct](jwt_auth.JwtParams{
SigningAlgorithm: "HS256",
Timeout: "1h",
MaxRefresh: "1h",
TokenLookup: "header: Authorization",
TokenHeadName: "Bearer",
IdentityKey: "username",
})
middleware.IdentityHandler = yourIdentityHandler // Reference 'example/users/jwt.go' for implementation
middleware.Authenticator = yourAuthenticator
middleware.Authorizator = yourAuthorizator
// Step 3: Create Gin jwt middleware instance
middleware, err := jwt.New(params)
if err != nil {
log.Fatalf("[ERR]: error creating JWT middleware\n")
}
// Step 4: Register routes and middleware
mwh, err := auth.MiddlewareHandler(middleware)
if err != nil {
log.Fatalf("[ERR]: error creating JWT middleware handler (%v)\n", err)
}
group.Use(mwh)
auth.RegisterRoute(group, middleware)
// Step 4: Use middleware for protected routes
api.GET("/protected", middleware.MiddlewareFunc(), func(c *gin.Context) {
// Access claims via jwt.ExtractClaims(c)
})
Design Decisions:
- User Interface: Users must implement a `user` interface containing `GetUsername()`
- Generic Support: `GenerateParams` uses generics, allowing flexible user object types
- Pluggable Logic: Core JWT functions like `Authenticator`, `Authorizator`, and `IdentityHandler` are left undefined to allow for custom `user` struct implementations
Types:
- JwtParams: Configuration for token duration, signing algorithm, lookup method, etc
- JwtRequest / JwtResponse: Structs for token exchange requests and responses
- User: Interface for user models to expose a username/identity key
This package provides a clean foundation for stateless authentication while staying modular enough to support advanced needs or unconventional flows
Handle JWT authentication using the gin-jwt middleware
Index ¶
- func GenerateParams[T User](params JwtParams) (*jwt.GinJWTMiddleware, error)
- func HandleNoRoute(c *gin.Context)
- func MiddlewareHandler(mw *jwt.GinJWTMiddleware) (gin.HandlerFunc, error)
- func RegisterRoute(g *gin.RouterGroup, handle *jwt.GinJWTMiddleware, prefix ...string) error
- func SetSecretKey(jwtSecret string) error
- type JwtParams
- type JwtRequest
- type JwtResponse
- type User
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GenerateParams ¶
func GenerateParams[T User](params JwtParams) (*jwt.GinJWTMiddleware, error)
Generate default JWT parameters for the middleware
func HandleNoRoute ¶
Handle requests with no route and log the claims
func MiddlewareHandler ¶
func MiddlewareHandler(mw *jwt.GinJWTMiddleware) (gin.HandlerFunc, error)
Middleware handler for JWT authentication
func RegisterRoute ¶
func RegisterRoute(g *gin.RouterGroup, handle *jwt.GinJWTMiddleware, prefix ...string) error
Register JWT routes with the given middleware. An optional prefix can be provided
func SetSecretKey ¶
SetSecretKey sets the JWT secret key used for signing tokens
Types ¶
type JwtParams ¶
type JwtParams struct {
SigningAlgorithm string `json:"signing_algorithm"`
Timeout string `json:"timeout"`
MaxRefresh string `json:"max_refresh"`
TokenLookup string `json:"token_lookup"`
TokenHeadName string `json:"token_head_name"`
IdentityKey string `json:"identity_key"`
}
JwtParams represents the parameters provided for JWT authentication. These are passed by the user to the 'Param' function. These are specified by Gin JWT middleware
type JwtRequest ¶
JwtRequest represents the incoming request for a JWT token