jwt

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package jwt 提供 RS256 的 JWT 签发与校验。

硬契约(与既有消费方互通,不可改):

  • alg 恰为 RS256
  • JWT header 只含 {"alg":"RS256"},不带 typ
  • 业务自定义声明平铺进 payload,解析时收集进 Claims.Extra

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidToken = errors.New("jwt: invalid token")

ErrInvalidToken 表示令牌无法解析或校验失败。

Functions

func MarshalKeyPairPEM

func MarshalKeyPairPEM(kp *KeyPair) (privPEM, pubPEM string, err error)

MarshalKeyPairPEM 把密钥对编为 PEM(私钥 PKCS#1,公钥 PKIX)。

func ParsePrivateKey

func ParsePrivateKey(pemBytes []byte) (*rsa.PrivateKey, error)

ParsePrivateKey 解析 PEM 私钥(PKCS#1 / PKCS#8)。

func ParsePublicKey

func ParsePublicKey(pemBytes []byte) (*rsa.PublicKey, error)

ParsePublicKey 解析 PEM 公钥(PKIX / PKCS#1),也接受 X.509 证书。

func Sign

func Sign(kp *KeyPair, opts ...SignOption) (string, error)

Sign 用 RS256 签发令牌。iat 恒为当前时刻;ttl 缺省 24h。

Types

type Claims

type Claims struct {
	gojwt.RegisteredClaims
	// Extra 承载业务自定义声明(签发时经 WithClaim 平铺进 payload,解析时收集回来)。
	Extra map[string]any
}

Claims 是签发与解析的载荷容器。

func Parse

func Parse(token string, pub *rsa.PublicKey, opts ...ParseOption) (*Claims, error)

Parse 校验并解析令牌(RS256-only,缺省零 leeway)。

已注册声明(iss/sub/jti/exp/iat/nbf)收进 RegisteredClaims;其余(含 aud)进 Extra。

type KeyPair

type KeyPair struct {
	Private *rsa.PrivateKey
	Public  *rsa.PublicKey
}

KeyPair 持有 RS256 的密钥对。

func GenerateKeyPair

func GenerateKeyPair(bits int) (*KeyPair, error)

GenerateKeyPair 生成 RSA 密钥对(bits < 2048 时按 2048 处理)。

type ParseOption

type ParseOption func(*parseOptions)

ParseOption 是 Parse 的函数选项。

func WithLeeway

func WithLeeway(d time.Duration) ParseOption

WithLeeway 设置时钟偏移容忍。

type SignOption

type SignOption func(*signOptions)

SignOption 是 Sign 的函数选项。

func WithClaim

func WithClaim(key string, val any) SignOption

WithClaim 追加一个业务自定义声明。

func WithIssuer

func WithIssuer(iss string) SignOption

WithIssuer 设置 iss。

func WithJTI

func WithJTI(jti string) SignOption

WithJTI 设置 jti(令牌 ID)。

func WithNotBefore

func WithNotBefore(t time.Time) SignOption

WithNotBefore 设置 nbf。

func WithSubject

func WithSubject(sub string) SignOption

WithSubject 设置 sub。

func WithTTL

func WithTTL(d time.Duration) SignOption

WithTTL 设置 exp = iat + ttl。零值 = 不写 exp。

Jump to

Keyboard shortcuts

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