Documentation
¶
Index ¶
- Variables
- func ExtractClaims(c *gin.Context) jwt.MapClaims
- func ExtractClaimsFromToken(token *jwt.Token) jwt.MapClaims
- func GetToken(c *gin.Context) string
- type GinJWTMiddleware
- func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error)
- func (mw *GinJWTMiddleware) ClearSensitiveData()
- func (mw *GinJWTMiddleware) EnableRedisStore(opts ...RedisOption) *GinJWTMiddleware
- func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (jwt.MapClaims, error)
- func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context)
- func (mw *GinJWTMiddleware) LogoutHandler(c *gin.Context)
- func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc
- func (mw *GinJWTMiddleware) MiddlewareInit() error
- func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error)
- func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error)
- func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context)
- func (mw *GinJWTMiddleware) SetCookie(c *gin.Context, token string)
- func (mw *GinJWTMiddleware) TokenGenerator(ctx context.Context, data any) (*core.Token, error)
- func (mw *GinJWTMiddleware) TokenGeneratorWithRevocation(ctx context.Context, data any, oldRefreshToken string) (*core.Token, error)
- type RedisOption
- func WithRedisAddr(addr string) RedisOption
- func WithRedisAuth(password string, db int) RedisOption
- func WithRedisCache(size int, ttl time.Duration) RedisOption
- func WithRedisKeyPrefix(prefix string) RedisOption
- func WithRedisPool(poolSize int, maxIdleTime, maxLifetime time.Duration) RedisOption
- func WithRedisTLS(tlsConfig *tls.Config) RedisOption
Constants ¶
This section is empty.
Variables ¶
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 ¶
ExtractClaims help to extract the JWT claims
func ExtractClaimsFromToken ¶
ExtractClaimsFromToken help to extract the JWT claims from token
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
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 ¶
func New(m *GinJWTMiddleware) (*GinJWTMiddleware, error)
New creates and initializes a new GinJWTMiddleware instance
func (*GinJWTMiddleware) CheckIfTokenExpire ¶
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 ¶
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 ¶
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 ¶
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
func WithRedisTLS ¶ added in v3.2.0
func WithRedisTLS(tlsConfig *tls.Config) RedisOption
WithRedisTLS sets the TLS configuration for secure connections
Directories
¶
| Path | Synopsis |
|---|---|
|
_example
|
|
|
redis_simple
command
|
|
|
redis_tls
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 |

