jwt

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

README

JWT

A JWT plugin for gin, iris, go-frame, beego, go-zero, go-chassis, go-kit and other frameworks

Use

Download and install

go get github.com/devagame/jwt

Demo

package main

import (
	"fmt"
	"log"
	"github.com/devagame/jwt"
)

func main() {
	auth, err := jwt.NewJWT(
		jwt.WithIssuer("backend"),
		jwt.WithSignAlgorithm(jwt.HS256),
		jwt.WithSecretKey("secret"),
		jwt.WithValidDuration(3600),
		jwt.WithLookupLocations("header:Authorization"),
		jwt.WithIdentityKey("uid"),
	)
	if err != nil {
		log.Fatal("create jwt instance failed:" + err.Error())
    }

	token, err := auth.GenerateToken(jwt.Payload{
		"uid":     1,
		"account": "fuxiao",
	})
	if err != nil {
		log.Fatal("Generate token failed:" + err.Error())
	}

	fmt.Println(token)
}

Example

View demo example/server.go

API Demo

View demo example/jwt.postman.json

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingToken indicates JWT token is missing
	ErrMissingToken = errors.New("token is missing")

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

	// ErrInvalidToken indicates auth header is invalid, could for example have the wrong issuer
	ErrInvalidToken = errors.New("token is invalid")

	// ErrMissingIdentity indicates that there is no corresponding identity information in the payload
	ErrMissingIdentity = errors.New("identity is missing")

	// ErrAuthElsewhere indicates that the same identity is logged in elsewhere
	ErrAuthElsewhere = errors.New("auth elsewhere")

	// ErrSignAlgorithmNotMatch indicates that the signing method of the token is inconsistent with the configured signing method
	ErrSignAlgorithmNotMatch = errors.New("sign algorithm does not match")

	// ErrInvalidSignAlgorithm indicates that the sign algorithm is invalid, must be one of HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384 and ES512
	ErrInvalidSignAlgorithm = errors.New("invalid sign algorithm")

	// ErrInvalidSecretKey indicates that the given secret cacheKey is invalid
	ErrInvalidSecretKey = errors.New("invalid secret cacheKey")

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

	// ErrInvalidPublicKey indicates the given public cacheKey is invalid
	ErrInvalidPublicKey = errors.New("invalid public cacheKey")
)

Functions

func IsAuthElsewhere

func IsAuthElsewhere(err error) bool

func IsExpiredToken

func IsExpiredToken(err error) bool

func IsIdentityMissing

func IsIdentityMissing(err error) bool

func IsInvalidSignAlgorithm

func IsInvalidSignAlgorithm(err error) bool

func IsInvalidToken

func IsInvalidToken(err error) bool

func IsMissingToken

func IsMissingToken(err error) bool

Types

type Http

type Http struct {
	// contains filtered or unexported fields
}

func NewHttp

func NewHttp(jwt *JWT) *Http

func (*Http) DestroyToken

func (h *Http) DestroyToken(r *http.Request) error

DestroyToken Destroy a token. By default, the token expired error be ignored.

func (*Http) ExtractIdentity

func (h *Http) ExtractIdentity(r *http.Request, ignoreExpired ...bool) (interface{}, error)

ExtractIdentity Retrieve identity from request. By default, the token expired error doesn't be ignored. You can ignore expired error by setting the `ignoreExpired` parameter.

func (*Http) ExtractPayload

func (h *Http) ExtractPayload(r *http.Request, ignoreExpired ...bool) (payload Payload, err error)

ExtractPayload Retrieve payload from request. By default, the token expired error doesn't be ignored. You can ignore expired error by setting the `ignoreExpired` parameter.

func (*Http) ExtractToken

func (h *Http) ExtractToken(r *http.Request, ignoreExpired ...bool) (*Token, error)

ExtractToken Extracts and returns a token object from request. By default, the token expired error doesn't be ignored. You can ignore expired error by setting the `ignoreExpired` parameter.

func (*Http) Middleware

func (h *Http) Middleware(r *http.Request) (*http.Request, error)

Middleware Implemented basic JWT permission authentication.

func (*Http) RefreshToken

func (h *Http) RefreshToken(r *http.Request, ignoreExpired ...bool) (*Token, error)

RefreshToken Generates and returns a new token object from request. By default, the token expired error doesn't be ignored. You can ignore expired error by setting the `ignoreExpired` parameter.

type JWT

type JWT struct {
	// contains filtered or unexported fields
}

func NewJWT

func NewJWT(opts ...Option) (*JWT, error)

func (*JWT) DestroyIdentity

func (j *JWT) DestroyIdentity(identity interface{}) error

DestroyIdentity Destroy the identification mark.

func (*JWT) DestroyToken

func (j *JWT) DestroyToken(token string, ignoreExpired ...bool) error

DestroyToken Destroy a token.

func (*JWT) ExtractIdentity

func (j *JWT) ExtractIdentity(token string, ignoreExpired ...bool) (interface{}, error)

ExtractIdentity Retrieve identity from token. By default, the token expired error doesn't be ignored. You can ignore expired error by setting the `ignoreExpired` parameter.

func (*JWT) ExtractPayload

func (j *JWT) ExtractPayload(token string, ignoreExpired ...bool) (Payload, error)

ExtractPayload Extracts and returns payload from the token. By default, The token expiration errors will not be ignored. The payload is nil when the token expiration errors not be ignored.

func (*JWT) GenerateToken

func (j *JWT) GenerateToken(payload Payload) (*Token, error)

GenerateToken Generates and returns a new token object with payload.

func (*JWT) Http

func (j *JWT) Http() *Http

Http Create a http jwt component

func (*JWT) IdentityKey

func (j *JWT) IdentityKey() string

IdentityKey Retrieve identity key.

func (*JWT) RefreshToken

func (j *JWT) RefreshToken(token string, ignoreExpired ...bool) (*Token, error)

RefreshToken Retreads and returns a new token object depend on old token. By default, the token expired error doesn't be ignored. You can ignore expired error by setting the `ignoreExpired` parameter.

type Option

type Option func(o *options)

func WithIdentityKey

func WithIdentityKey(identityKey string) Option

WithIdentityKey Set the identity key of the token. After opening the identification identifier and cache interface, the system will construct a unique authorization identifier for each token. If the same user is authorized to log in elsewhere, the previous token will no longer be valid.

func WithIssuer

func WithIssuer(issuer string) Option

WithIssuer Set the issuer of the token.

func WithLookupLocations

func WithLookupLocations(locations string) Option

WithLookupLocations Set the token lookup locations within requests. Support header, form, cookie and query parameter. Support to seek multiple locations, Separate multiple seek locations with commas.

func WithPublicPrivateKey

func WithPublicPrivateKey(publicKey, privateKey string) Option

WithPublicPrivateKey Set public key and private key. The signature algorithm is one of RS256, RS384, RS512, ES256, ES384 and ES512

func WithRefreshDuration

func WithRefreshDuration(duration int) Option

WithRefreshDuration Set token refresh duration.

func WithSecretKey

func WithSecretKey(secretKey string) Option

WithSecretKey Set secret key. The signature algorithm is one of HS256, HS384 and HS512

func WithSignAlgorithm

func WithSignAlgorithm(signAlgorithm SignAlgorithm) Option

WithSignAlgorithm Set signature algorithm. The secret key must be set when the signature algorithm is one of HS256, HS384 and HS512 The public key and private key must be set when the signature algorithm is one of RS256, RS384 and RS512 The public key and private key must be set when the signature algorithm is one of ES256, ES384 and ES512

func WithStore

func WithStore(store Store) Option

WithStore Set a store adapter for authentication.

func WithValidDuration

func WithValidDuration(duration int) Option

WithValidDuration Set token valid duration. If only set the valid duration, The refresh duration will automatically be set to half of the valid duration.

type Payload

type Payload map[string]interface{}

type SignAlgorithm

type SignAlgorithm string
const (
	HS256 SignAlgorithm = "HS256"
	HS512 SignAlgorithm = "HS512"
	HS384 SignAlgorithm = "HS384"

	RS256 SignAlgorithm = "RS256"
	RS384 SignAlgorithm = "RS384"
	RS512 SignAlgorithm = "RS512"

	ES256 SignAlgorithm = "ES256"
	ES384 SignAlgorithm = "ES384"
	ES512 SignAlgorithm = "ES512"
)

func (SignAlgorithm) String

func (s SignAlgorithm) String() string

type Store

type Store interface {
	Get(ctx context.Context, key interface{}) (interface{}, error)

	Set(ctx context.Context, key interface{}, value interface{}, duration time.Duration) error

	Remove(ctx context.Context, keys ...interface{}) (value interface{}, err error)
}

type Token

type Token struct {
	Token     string    `json:"token"`
	ExpiredAt time.Time `json:"expired_at"`
	RefreshAt time.Time `json:"refresh_at"`
}

Directories

Path Synopsis
internal