jwt

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TokenHeaderKey      = "X-Token"
	TokenQueryStringKey = "token"
)

Variables

This section is empty.

Functions

func MustParseJWTUser

func MustParseJWTUser(ctx *gin.Context, opt *Option) (*httpcontext.User, error)

MustParseJWTUser 解析 jwt User 信息。如果是静默模式(SilentMode=true), User.ID 可能为零

Types

type IToken

type IToken interface {
	// SetIssuer 设置 token 发行人,默认为 "go-pkg"
	SetIssuer(issuer string) IToken
	// SetDuration 设置 token 过期时长,默认为 24h
	SetDuration(d time.Duration) IToken
	// SetSecret 设置 token 加密密钥,默认 "go-pkg.JwtSecret"
	SetSecret(secret []byte) IToken
	// SetData 设置 token 扩展数据
	SetData(key string, val string) IToken

	GetUser(fun httpcontext.ToRole) (*httpcontext.User, error)

	// IsStateful 是否为有状态 jwt token
	// 主要用于解决 jwt token 无状态,颁发后不可控。需要业务端注入处理函数
	IsStateful() bool
	// IsExpired 是否过期
	IsExpired() bool

	// Refresh 刷新 token
	Refresh()
	// RefreshNear 自动刷新 token,如果当前时间临近过期时间
	RefreshNear(d time.Duration)

	// ToString 转成 token 字符串
	ToString() (string, error)
}

func NewStatefulToken

func NewStatefulToken(user httpcontext.User, handler StatefulStore) IToken

NewStatefulToken 初始化有状态的 Token 默认发行人为 "go-pkg",可以通过 WithIssuer 修改; 默认有效期为 24h,可以通过 WithDuration 设置有效时长

func NewToken

func NewToken(user httpcontext.User) IToken

NewToken 初始化 Token 默认发行人为 "go-pkg",可以通过 WithIssuer 修改; 默认有效期为 24h,可以通过 WithDuration 设置有效时长

func ParseTokenWithGin

func ParseTokenWithGin(ctx *gin.Context) (IToken, error)

ParseTokenWithGin 通过 gin.Context 初始化 token 从 gin.Context 优先读取 http header 中的 X-Token 值;如果不存在,则读取 query string 中的 token 值

func ParseTokenWithSecret

func ParseTokenWithSecret(ctx *gin.Context, secret []byte) (string, IToken, error)

ParseTokenWithSecret 解析 token

type Option

type Option struct {
	// 角色转化函数,转换成角色 IRole
	RoleConvert httpcontext.ToRole

	// 过期自动刷新临界时长。零则表示不自动刷新
	RefreshDuration time.Duration

	// token 加密密钥。默认为 "go-pkg.JwtSecret"
	Secret []byte

	// 是否开启静默模式。true-开启:鉴权失败,不注入用户信息;false-关闭。鉴权失败阻断,并抛出错误
	SilentMode bool
}

Option jwt 配置参数

func (*Option) WithSilent

func (o *Option) WithSilent(enable bool) *Option

WithSilent 设置是否开启静默模式

type StatefulStore

type StatefulStore interface {
	// Save token 状态存储器
	Save(userID uint, token string, expireTs int64) error
	// Check token 状态检查器
	Check(userID uint, token string) error
	// Remove 删除指定 token
	Remove(userID uint, token string) error
	// Clean 清理用户的所有 token
	Clean(userID uint) error
}

StatefulStore 状态存储

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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