mjwt

package
v0.0.0-...-889a1ee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2024 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// TokenKey default jwt token key in params
	TokenKey = "JWT_TOKEN"
	// PayloadKey default jwt payload key in params
	PayloadKey = "JWT_PAYLOAD"
	// IdentityKey default identity key
	IdentityKey = "identity"
)
View Source
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("JWTMiddleware.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")

	// ErrNoPrivateKeyFile indicates that the given private key is unreadable
	ErrNoPrivateKeyFile = errors.New("private key file unreadable")

	// ErrNoPubKeyFile indicates that the given public key is unreadable
	ErrNoPubKeyFile = errors.New("public key file unreadable")

	// ErrInvalidPrivateKey indicates that the given private key is invalid
	ErrInvalidPrivateKey = errors.New("private key invalid")

	// ErrInvalidPubKey indicates the the given public key is invalid
	ErrInvalidPubKey = errors.New("public key invalid")

	// ErrMissingIdentity identity key and identity value is null
	ErrMissingIdentity = errors.New("payload don't have identity key and identity value")

	// ErrMissingContext indicates Context is required
	ErrMissingContext = errors.New("context is required")

	// ErrInvalidToken indicates JWT token has invalid. Can't refresh.
	ErrInvalidToken = errors.New("token is invalid")
)

Functions

This section is empty.

Types

type ManageJwt

type ManageJwt struct {
	//登录路径
	LoginPaths []string
	//退出路径
	LogoutPaths []string

	// 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) (interface{}, error)

	// 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(ctx context.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.
	Authorizer func(data interface{}, ctx context.Context) bool

	// Callback function that will be called during login.
	// Using this function it is possible to add additional payload data to the web token.
	// The data is then made available during requests via c.Get(jwt.PayloadKey).
	// 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

	// User can define own Unauthorized func.
	// 没有通过授权时的处理方法
	Unauthorized func(ctx context.Context, code int, message string)

	// Set the identity handler function
	// 身份标识提取函数
	IdentityHandler func(ctx context.Context) interface{}

	// 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>"
	TokenLookups []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, ctx context.Context) string

	// Private key file for asymmetric algorithms
	PrivateKeyFile string

	// Private Key bytes for asymmetric algorithms
	//
	// Note: PrivateKeyFile takes precedence over PrivateKeyBytes if both are set
	PrivateKeyBytes []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

	// CacheAdapter
	CacheAdapter gcache.Adapter

	// BlacklistPrefix
	BlacklistPrefix string

	//排除的路径
	ExcludePaths []string
	// contains filtered or unexported fields
}

ManageJwt 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 管理台Jwt配置对象

func New

func New(options ...Option) *ManageJwt

New for check error with ManageJwt

func (*ManageJwt) AuthPath

func (mw *ManageJwt) AuthPath(ctx context.Context, urlPath string) bool

AuthPath 判断路径是否需要进行认证拦截 return true 需要认证

func (*ManageJwt) CheckIfTokenExpire

func (mw *ManageJwt) CheckIfTokenExpire(ctx context.Context) (jwt.MapClaims, string, error)

CheckIfTokenExpire check if token expire

func (*ManageJwt) GetClaimsFromJWT

func (mw *ManageJwt) GetClaimsFromJWT(ctx context.Context) (MapClaims, string, error)

GetClaimsFromJWT get claims from JWT token

func (*ManageJwt) LoginHandler

func (mw *ManageJwt) LoginHandler(ctx context.Context) (tokenString string, expire time.Time)

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 (*ManageJwt) LogoutHandler

func (mw *ManageJwt) LogoutHandler(ctx context.Context)

LogoutHandler can be used by clients to remove the jwt cookie (if set)

func (*ManageJwt) MiddlewareFunc

func (mw *ManageJwt) MiddlewareFunc() ghttp.HandlerFunc

MiddlewareFunc makes ManageJwt implement the Middleware interface.

func (*ManageJwt) RefreshHandler

func (mw *ManageJwt) RefreshHandler(ctx context.Context) (tokenString string, expire time.Time)

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 ManageJwt. Reply will be of the form {"token": "TOKEN"}.

func (*ManageJwt) RefreshToken

func (mw *ManageJwt) RefreshToken(ctx context.Context) (string, time.Time, error)

RefreshToken refresh token and check if token is expired

func (*ManageJwt) TokenGenerator

func (mw *ManageJwt) TokenGenerator(data interface{}) (string, time.Time, error)

TokenGenerator method that clients can use to get a jwt token.

type MapClaims

type MapClaims map[string]interface{}

MapClaims type that uses the map[string]interface{} for JSON decoding This is the default claims type if you don't supply one jwt token内容

func ExtractClaims

func ExtractClaims(ctx context.Context) MapClaims

ExtractClaims help to extract the JWT claims

func ExtractClaimsFromToken

func ExtractClaimsFromToken(token *jwt.Token) MapClaims

ExtractClaimsFromToken help to extract the JWT claims from token

type Option

type Option func(cfg *ManageJwt)

Option 定义函数选项类型

func WithAuthenticator

func WithAuthenticator(authenticator func(ctx context.Context) (interface{}, error)) Option

WithAuthenticator 设置认证操作

func WithAuthorizer

func WithAuthorizer(authorizer func(data interface{}, ctx context.Context) bool) Option

WithAuthorizer 设置授权操作

func WithKey

func WithKey(key []byte) Option

WithKey 设置密钥

func WithKeyFunc

func WithKeyFunc(keyFunc func(token *jwt.Token) (interface{}, error)) Option

WithKeyFunc 设置解析token处理方法

func WithLoginPaths

func WithLoginPaths(loginPaths ...string) Option

WithLoginPaths 设置登录路径

func WithLogoutPaths

func WithLogoutPaths(logoutPaths ...string) Option

WithLogoutPaths 设置退出路径

func WithMaxRefresh

func WithMaxRefresh(maxRefresh time.Duration) Option

WithMaxRefresh 设置token可刷新时间

func WithPayloadFunc

func WithPayloadFunc(payloadFunc func(data interface{}) MapClaims) Option

WithPayloadFunc payload处理方法

func WithRealm

func WithRealm(realm string) Option

WithRealm 设置Realm

func WithSigningAlgorithm

func WithSigningAlgorithm(signingAlgorithm string) Option

WithSigningAlgorithm 设置签名算法

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout 设置token超时时间

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL