jwt

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2022 License: MIT Imports: 12 Imported by: 0

README

gf-jwt

GF jwt plugin

This plugin is forked https://github.com/appleboy/gin-jwt plugin, modified to https://github.com/gogf/gf plugin.

英文 中文

Use

Download and install

$ go get github.com/gogf/gf-jwt

Import

import "github.com/gogf/gf-jwt"

Demo

Run example/main.go on the 8000 port.

$ go run example/main.go

api screenshot

Test the effect on the command line via httpie or curl.

Login interface:
$ http -v --form POST localhost:8000/login username=admin password=admin

or

$ curl -X POST -d 'username=admin&password=admin' localhost:8000/login

Command line output

api screenshot

Refresh token interface:
$ http -v -f GET localhost:8000/refresh_token "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"

or

$ curl -H 'Authorization:Bearer xxxxxxxxx' -X POST localhost:8000/refresh_token

Command line output

api screenshot

User info interface

We test the return of the info interface with the username admin and password admin

$ http -f GET localhost:8000/user/info "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"

or

$ curl -H 'Authorization:Bearer xxxxxx' -X POST localhost:8000/user/info

Command line output

api screenshot

User Authentication Interface

We use an unauthorized token to test the return of the hello interface.

$ http -f GET localhost:8000/user/info "Authorization:Bearer xxxxxxxxx" "Content-Type: application/json"

or

curl -H 'Authorization:Bearer xxxxxx' -X POST localhost:8000/user/info

Command line output

api screenshot

Thanks again https://github.com/appleboy/gin-jwt

Documentation

Index

Constants

This section is empty.

Variables

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("GfJWTMiddleware.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")

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

	// 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")

	// 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")

	// ErrMissingIdentity identity key and identity value is null
	ErrMissingIdentity = errors.New("payload don't have identity key and identity value")
)
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"
)

Functions

func GetToken

func GetToken(r *ghttp.Request) string

GetToken help to get the JWT token string

Types

type GfJWTMiddleware

type GfJWTMiddleware 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(r *ghttp.Request) (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{}, r *ghttp.Request) 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.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(*ghttp.Request, int, string)

	// User can define own LoginResponse func.
	LoginResponse func(*ghttp.Request, int, string, time.Time)

	// User can define own RefreshResponse func.
	RefreshResponse func(*ghttp.Request, int, string, time.Time)

	// User can define own LogoutResponse func.
	LogoutResponse func(*ghttp.Request, int)

	// Set the identity handler function
	IdentityHandler func(*ghttp.Request) 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>"
	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, r *ghttp.Request) 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

	// CacheAdapter
	CacheAdapter gcache.Adapter
	// contains filtered or unexported fields
}

GfJWTMiddleware 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 GfJWTMiddleware

func (*GfJWTMiddleware) CheckIfTokenExpire

func (mw *GfJWTMiddleware) CheckIfTokenExpire(r *ghttp.Request) (jwt.MapClaims, string, error)

CheckIfTokenExpire check if token expire

func (*GfJWTMiddleware) GetClaimsFromJWT

func (mw *GfJWTMiddleware) GetClaimsFromJWT(r *ghttp.Request) (MapClaims, string, error)

GetClaimsFromJWT get claims from JWT token

func (*GfJWTMiddleware) LoginHandler

func (mw *GfJWTMiddleware) LoginHandler(r *ghttp.Request)

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

func (mw *GfJWTMiddleware) LogoutHandler(r *ghttp.Request)

LogoutHandler can be used to logout a token. The token still needs to be valid on logout. Logout the token puts the unexpired token on a blacklist.

func (*GfJWTMiddleware) MiddlewareFunc

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

MiddlewareFunc makes GfJWTMiddleware implement the Middleware interface.

func (*GfJWTMiddleware) MiddlewareInit

func (mw *GfJWTMiddleware) MiddlewareInit() error

MiddlewareInit initialize jwt configs.

func (*GfJWTMiddleware) ParseToken

func (mw *GfJWTMiddleware) ParseToken(r *ghttp.Request) (*jwt.Token, error)

ParseToken parse jwt token

func (*GfJWTMiddleware) RefreshHandler

func (mw *GfJWTMiddleware) RefreshHandler(r *ghttp.Request)

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

func (*GfJWTMiddleware) RefreshToken

func (mw *GfJWTMiddleware) RefreshToken(r *ghttp.Request) (string, time.Time, error)

RefreshToken refresh token and check if token is expired

func (*GfJWTMiddleware) TokenGenerator

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

func ExtractClaims

func ExtractClaims(r *ghttp.Request) MapClaims

ExtractClaims help to extract the JWT claims

Jump to

Keyboard shortcuts

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