Documentation ¶
Index ¶
- Constants
- Variables
- func GetToken(c *gin.Context) string
- type GinJWTMiddleware
- func (mw *GinJWTMiddleware[SessInf]) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error)
- func (mw *GinJWTMiddleware[SessInf]) GetClaimsFromJWT(c *gin.Context) (MapClaims, error)
- func (mw *GinJWTMiddleware[SessInf]) LoginHandler(c *gin.Context)
- func (mw *GinJWTMiddleware[SessInf]) MiddlewareFunc() gin.HandlerFunc
- func (mw *GinJWTMiddleware[SessInf]) MiddlewareInit() error
- func (mw *GinJWTMiddleware[SessInf]) ParseToken(c *gin.Context) (*jwt.Token, error)
- func (mw *GinJWTMiddleware[SessInf]) ParseTokenString(token string) (*jwt.Token, error)
- func (mw *GinJWTMiddleware[SessInf]) RefreshHandler(c *gin.Context)
- func (mw *GinJWTMiddleware[SessInf]) RefreshToken(c *gin.Context) (string, time.Time, error)
- func (mw *GinJWTMiddleware[SessInf]) TokenGenerator(data interface{}) (string, time.Time, error)
- type GinSessionAuth
- type GinSessionOption
- func SessionWithCustomLoginHandler(arg IAuthLoginHandler) GinSessionOption
- func SessionWithExpired(arg int) GinSessionOption
- func SessionWithGinCtxSessionKey(arg string) GinSessionOption
- func SessionWithPrefixKey(arg string) GinSessionOption
- func SessionWithSessionInfoConstructor(arg func(map[string]string) (user.ISessionInfo, error)) GinSessionOption
- func SessionWithStorage(arg storage.AdapterCache) GinSessionOption
- func SessionWithTokenLookup(arg []string) GinSessionOption
- func SessionWithTokenName(arg string) GinSessionOption
- type IAuth
- type IAuthLoginHandler
- type LoginResponse
- type MapClaims
Constants ¶
const JwtPayloadKey = "JWT_PAYLOAD"
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 or Code") // 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") // 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 cokie 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") ErrInvalidVerificationode = errors.New("验证码错误") // 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" // NiceKey 昵称 NiceKey = "nice" DataScopeKey = "datascope" RKey = "r" // RoleIdKey 角色id Old RoleIdKey = "roleid" // RoleKey 角色名称 Old RoleKey = "rolekey" // RoleNameKey 角色名称 Old RoleNameKey = "rolename" // RoleIdKey 部门id DeptId = "deptId" // RoleKey 部门名称 DeptName = "deptName" )
Functions ¶
Types ¶
type GinJWTMiddleware ¶
type GinJWTMiddleware[SessInf user.ISessionInfo] struct { // Realm name to display to the user. Required. Realm string // signing algorithm - possible values are HS256, HS384, HS512 // Optional, default is HS256. SigningAlgorithm string // Secret key used for signing. Required. Key []byte // Duration that a jwt token is valid. Optional, defaults to one hour. Timeout 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) (interface{}, 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. Authorizator func(data interface{}, c *gin.Context) 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 interface{}) MapClaims Unauthorized func(*gin.Context, int, string) // User can define own LoginResponse func. LoginResponse func(*gin.Context, int, string, time.Time) // User can define own AntdLoginResponse func. AntdLoginResponse func(*gin.Context, int, string, time.Time) // User can define own RefreshResponse func. RefreshResponse func(*gin.Context, int, string, time.Time) // Set the identity handler function IdentityHandler func(*gin.Context) interface{} // 关键字段,用于存储用户信息 // Set the identity key IdentityKey string // 用户名 NiceKey string // 数据权限类型 DataScopeKey string // role key RKey string // 角色id RoleIdKey string // 角色key RoleKey string // 角色名称 RoleNameKey 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(e error, c *gin.Context) string // Private key file for asymmetric algorithms PrivKeyFile string // Public key file for asymmetric algorithms PubKeyFile string // Optionally return the token as a cookie SendCookie bool // 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 SessionInfoConstructor func(map[string]string) (SessInf, error) // 会话信息构造函数 // 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[SessInf user.ISessionInfo](m *GinJWTMiddleware[SessInf]) (*GinJWTMiddleware[SessInf], error)
New for check error with GinJWTMiddleware
func (*GinJWTMiddleware[SessInf]) CheckIfTokenExpire ¶
func (mw *GinJWTMiddleware[SessInf]) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error)
CheckIfTokenExpire check if token expire
func (*GinJWTMiddleware[SessInf]) GetClaimsFromJWT ¶
func (mw *GinJWTMiddleware[SessInf]) GetClaimsFromJWT(c *gin.Context) (MapClaims, error)
GetClaimsFromJWT get claims from JWT token
func (*GinJWTMiddleware[SessInf]) LoginHandler ¶
func (mw *GinJWTMiddleware[SessInf]) 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[SessInf]) MiddlewareFunc ¶
func (mw *GinJWTMiddleware[SessInf]) MiddlewareFunc() gin.HandlerFunc
MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface.
func (*GinJWTMiddleware[SessInf]) MiddlewareInit ¶
func (mw *GinJWTMiddleware[SessInf]) MiddlewareInit() error
MiddlewareInit initialize jwt configs.
func (*GinJWTMiddleware[SessInf]) ParseToken ¶
func (mw *GinJWTMiddleware[SessInf]) ParseToken(c *gin.Context) (*jwt.Token, error)
ParseToken parse jwt token from gin context
func (*GinJWTMiddleware[SessInf]) ParseTokenString ¶
func (mw *GinJWTMiddleware[SessInf]) ParseTokenString(token string) (*jwt.Token, error)
ParseTokenString parse jwt token string
func (*GinJWTMiddleware[SessInf]) RefreshHandler ¶
func (mw *GinJWTMiddleware[SessInf]) RefreshHandler(c *gin.Context)
RefreshHandler can be used to refresh a token. The token still needs to be valid on refresh. Shall be put under an endpoint that is using the GinJWTMiddleware. Reply will be of the form {"token": "TOKEN"}.
func (*GinJWTMiddleware[SessInf]) RefreshToken ¶
RefreshToken refresh token and check if token is expired
func (*GinJWTMiddleware[SessInf]) TokenGenerator ¶
func (mw *GinJWTMiddleware[SessInf]) TokenGenerator(data interface{}) (string, time.Time, error)
TokenGenerator method that clients can use to get a jwt token.
type GinSessionAuth ¶
type GinSessionAuth struct { Storage storage.AdapterCache // 缓存空间 PrefixKey string // 缓存key前缀 Expired int // 有效期(秒) GinCtxSessionKey string // gin上下文中的session key TokenName string // 获取token的key TokenLookup []string // 可以获取到token的位置 引文,分割 header,query,cookie SessionInfoConstructor func(map[string]string) (user.ISessionInfo, error) // 会话信息构造函数 CustomLoginHandler IAuthLoginHandler }
func (*GinSessionAuth) DeleteSession ¶
func (g *GinSessionAuth) DeleteSession(ctx *gin.Context) error
func (*GinSessionAuth) GetSessionInfo ¶
func (g *GinSessionAuth) GetSessionInfo(ctx *gin.Context) (user.ISessionInfo, error)
func (*GinSessionAuth) LoginHandler ¶
func (g *GinSessionAuth) LoginHandler(ctx *gin.Context)
func (*GinSessionAuth) MiddlewareFunc ¶
func (g *GinSessionAuth) MiddlewareFunc() gin.HandlerFunc
type GinSessionOption ¶
type GinSessionOption func(*GinSessionAuth)
func SessionWithCustomLoginHandler ¶
func SessionWithCustomLoginHandler(arg IAuthLoginHandler) GinSessionOption
func SessionWithGinCtxSessionKey ¶
func SessionWithGinCtxSessionKey(arg string) GinSessionOption
gin上下文中的session key
func SessionWithSessionInfoConstructor ¶
func SessionWithSessionInfoConstructor(arg func(map[string]string) (user.ISessionInfo, error)) GinSessionOption
会话信息构造函数
func SessionWithTokenLookup ¶
func SessionWithTokenLookup(arg []string) GinSessionOption
可以获取到token的位置 引文,分割 header,query,cookie
type IAuth ¶
type IAuth interface { // 会话验证 MiddlewareFunc() gin.HandlerFunc // 登录处理 LoginHandler(ctx *gin.Context) // 获取当前用户会话信息 GetSessionInfo(ctx *gin.Context) (user.ISessionInfo, error) // 删除会话 DeleteSession(ctx *gin.Context) error }
func NewGinSessionAuth ¶
func NewGinSessionAuth(opts ...GinSessionOption) (IAuth, error)
type IAuthLoginHandler ¶
type IAuthLoginHandler func(ctx *gin.Context) (user.ISessionInfo, error)
type LoginResponse ¶
type MapClaims ¶
type MapClaims map[string]interface{}
func ExtractClaims ¶
ExtractClaims help to extract the JWT claims
func ExtractClaimsFromToken ¶
func ExtractClaimsFromToken(token *jwt.Token) MapClaims
ExtractClaimsFromToken help to extract the JWT claims from token