token

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 4, 2026 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MinSecretLength 是 HS256 签名密钥的最小长度(32 字节 / 256 位).
	// HMAC-SHA256 的密钥强度不应低于其输出长度,过短的密钥可被暴力破解.
	MinSecretLength = 32
)

Variables

View Source
var (
	// ErrMissingHeader 表示 `Authorization` 请求头为空.
	//
	// Deprecated: ParseToken 现在返回带 HTTP 语义的 errno.ErrTokenMissing.
	ErrMissingHeader = errors.New("the length of the `Authorization` header is zero")

	// ErrBlacklistToken 表示存在于黑名单中的 token.
	//
	// Deprecated: ParseRequest 现在返回 errno.ErrTokenBlacklisted.
	ErrBlacklistToken = errors.New("token has in blacklist and expire")

	// ErrParseToken 表示解析 token 字符串失败.
	//
	// Deprecated: token 相关的解析错误现在尽量返回 *errno.Errno,便于 errno.Decode 统一处理.
	ErrParseToken = errors.New("parse token error")

	// ErrTokenNotInitialized 表示尚未通过 Init 配置 JWT 密钥.
	ErrTokenNotInitialized = errors.New("jwt token is not initialized")

	// ErrInvalidOptions 表示 Init 传入的配置为空.
	ErrInvalidOptions = errors.New("jwt options must not be nil")

	// ErrEmptySecret 表示 JWT 密钥为空.
	ErrEmptySecret = errors.New("jwt secret must not be empty")

	// ErrWeakSecret 表示 JWT 密钥长度不足 MinSecretLength 字节.
	ErrWeakSecret = errors.New("jwt secret is too short")
)

Functions

func AddToBlacklist

func AddToBlacklist(r *http.Request) error

AddToBlacklist 将会话级令牌(jti)加入黑名单,过期时间与 Token 一致

func FailureAllClient

func FailureAllClient(tokenId string) error

FailureAllClient 失效指定用户的所有 Token. 通过记录吊销时间点实现:该用户在吊销时间点之前签发的 token 都会被视为失效, 因此不受 config.Expire 后续调整的影响.

func Init

func Init(opts *Options) error

Init 校验并保存 JWT 配置. 应在签发或校验 token 之前调用(server.NewApplication 会自动完成接线). Secret 不能为空且长度不得小于 MinSecretLength 字节.

func IsBlacklisted

func IsBlacklisted(token *jwt.Token) (bool, error)

IsBlacklisted 检查 Token 是否已被吊销. 第一个返回值表示是否命中黑名单;第二个返回值表示吊销状态查询是否失败 (例如 Redis 不可用),调用方可据此记录告警.

注意:即使会话级(jti)查询失败,仍会继续检查用户级吊销时间点, 避免 Redis 抖动时 fail-open 分支完全跳过用户级吊销检查。

func ParseRequest

func ParseRequest(r *http.Request) (string, error)

ParseRequest 从请求头中获取令牌,并将其传递给 ParseToken 函数以解析令牌.

func ParseToken

func ParseToken(r *http.Request) (*jwt.Token, error)

ParseToken 解析令牌字符串为 jwt.Token 对象. 返回的错误尽量为 *errno.Errno,便于 errno.Decode 与 Authn 中间件做错误分类.

func Reset added in v0.1.3

func Reset()

Reset 清空当前 JWT 配置,供测试或进程重配使用.

func Sign

func Sign(tokenId string) (*response.TokenResponse, error)

Sign 使用配置中的密钥签发 token,token 的 claims 中会存放传入的 subject.

Types

type Options

type Options struct {
	// 用于存放唯一用户的字段
	TokenId string
	// jwt 秘钥(至少 MinSecretLength 字节)
	Secret string
	// token 过期时间(单位:小时)
	Expire int
	// 黑名单在 Redis 中的 key 前缀,默认为 jwt:blacklist:
	BlacklistPrefix string
	// 黑名单校验失败(如 Redis 不可用)时是否拒绝请求.
	// 默认 false:放行请求,保证鉴权可用性;对安全性要求高的场景应设为 true.
	BlacklistFailClosed bool
}

Options 包含与日志相关的配置项.

Jump to

Keyboard shortcuts

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