auth

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2022 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingSecretKey indicates Secret key is required
	ErrMissingSecretKey = fmt.Errorf("secret key is required")

	// ErrMissingAuthenticatorFunc indicates Authenticator is required
	ErrMissingAuthenticatorFunc = fmt.Errorf("ginJWTMiddleware.Authenticator func is undefined")

	// ErrFailedTokenCreation indicates JWT Token failed to create, reason unknown
	ErrFailedTokenCreation = fmt.Errorf("failed to create JWT Token")

	// ErrExpiredToken indicates JWT token has expired. Can't refresh.
	ErrExpiredToken = fmt.Errorf("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 = fmt.Errorf("auth header is empty")

	// ErrMissingExpField missing exp field in token
	ErrMissingExpField = fmt.Errorf("missing exp field")

	// ErrWrongFormatOfExp field must be float64 format
	ErrWrongFormatOfExp = fmt.Errorf("exp must be float64 format")

	// ErrInvalidAuthHeader indicates auth header is invalid, could for example have the wrong Realm name
	ErrInvalidAuthHeader = fmt.Errorf("auth header is invalid")

	// ErrEmptyQueryToken can be thrown if authing with URL Query, the query token variable is empty
	ErrEmptyQueryToken = fmt.Errorf("query token is empty")

	// ErrEmptyParamToken can be thrown if authing with parameter in path, the parameter in path is empty
	ErrEmptyParamToken = fmt.Errorf("parameter token is empty")

	// ErrInvalidSigningAlgorithm indicates signing algorithm is invalid, needs to be HS256, HS384, HS512
	ErrInvalidSigningAlgorithm = fmt.Errorf("invalid signing algorithm")

	// ErrFailedAuthentication indicates authentication failed, could be faulty username or password
	ErrFailedAuthentication = fmt.Errorf("incorrect Username or Password")

	// ErrMissingLoginValues indicates a user tried to authenticate without username or password
	ErrMissingLoginValues = fmt.Errorf("missing Username or Password")
)

Functions

This section is empty.

Types

type GinJWTMiddleware

type GinJWTMiddleware 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) (any, error)

	// 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_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) MapClaims

	// User can define own Unauthorized func.
	Unauthorized func(c *gin.Context, code int, err error)

	// User can define own LoginResponse func.
	LoginResponse func(c *gin.Context, code int, message string, time time.Time)

	// User can define own RefreshResponse func.
	RefreshResponse func(c *gin.Context, code int, message string, time time.Time)

	// TokenLookup is a stringutil 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 stringutil 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
}

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

New for check error with GinJWTMiddleware

func (*GinJWTMiddleware) CheckIfTokenExpire

func (mw *GinJWTMiddleware) CheckIfTokenExpire(c *gin.Context) (jwt.MapClaims, error)

CheckIfTokenExpire check if token expire

func (*GinJWTMiddleware) GetClaimsFromJWT

func (mw *GinJWTMiddleware) GetClaimsFromJWT(c *gin.Context) (MapClaims, error)

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) MiddlewareFunc

func (mw *GinJWTMiddleware) MiddlewareFunc() gin.HandlerFunc

MiddlewareFunc makes GinJWTMiddleware implement the Middleware interface.

func (*GinJWTMiddleware) MiddlewareInit

func (mw *GinJWTMiddleware) MiddlewareInit() error

MiddlewareInit initialize jwt configs.

func (*GinJWTMiddleware) ParseToken

func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error)

ParseToken parse jwt token from gin context

func (*GinJWTMiddleware) RefreshHandler

func (mw *GinJWTMiddleware) 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) RefreshToken

func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error)

RefreshToken refresh token and check if token is expired

type MapClaims

type MapClaims map[string]any

MapClaims type that uses the map[string]any for JSON decoding This is the default claims type if you don't supply one

func ExtractClaimsFromContext added in v0.3.0

func ExtractClaimsFromContext(c *gin.Context) MapClaims

ExtractClaimsFromContext help to extract the JWT claims

Jump to

Keyboard shortcuts

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