Documentation
¶
Overview ¶
Package jwt 提供JWT令牌的生成、解析和验证功能,支持多种签名算法。
核心特性:
- 支持多种签名算法:HS256/HS384/HS512、RS256、ES256等
- 提供简洁的API:Generate系列函数生成令牌,Parse系列函数解析令牌
- 内置Claims验证:支持过期时间、签发时间等标准声明验证
- 灵活的扩展性:支持自定义Claims结构
- 完善的错误处理:提供详细的错误信息便于调试
基本用法:
import (
loggermgr "github.com/lite-lake/litecore-go/component/manager/loggermgr"
)
loggerMgr := loggermgr.GetLoggerManager()
logger := loggerMgr.Logger("main")
// 生成HS256令牌
claims := &jwt.StandardClaims{
UserId: "123456",
Username: "john.doe",
ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
}
token, err := util.jwt.GenerateHS256Token(claims, "your-secret-key")
if err != nil {
logger.Fatal("Failed to generate token", "error", err)
}
// 解析HS256令牌
parsedClaims, err := util.jwt.ParseHS256Token(token, "your-secret-key")
if err != nil {
logger.Fatal("Failed to parse token", "error", err)
}
fmt.Printf("用户ID: %s, 用户名: %s\n", parsedClaims.UserId, parsedClaims.Username)
// 生成RS256令牌(使用私钥签名)
privateKey := []byte("-----BEGIN RSA PRIVATE KEY-----\n...")
token, err = util.jwt.GenerateRS256Token(claims, privateKey)
if err != nil {
logger.Fatal("Failed to generate token", "error", err)
}
// 解析RS256令牌(使用公钥验证)
publicKey := []byte("-----BEGIN PUBLIC KEY-----\n...")
parsedClaims, err = util.jwt.ParseRS256Token(token, publicKey)
if err != nil {
logger.Fatal("Failed to parse token", "error", err)
}
// 验证Claims
if err := util.jwt.ValidateClaims(parsedClaims); err != nil {
logger.Fatal("Failed to validate claims", "error", err)
}
支持的算法:
HMAC算法(对称加密):
- HS256: HMAC using SHA-256
- HS384: HMAC using SHA-384
- HS512: HMAC using SHA-512
非对称算法:
- RS256: RSASSA-PKCS1-v1_5 using SHA-256
- ES256: ECDSA using P-256 and SHA-256
Claims结构:
标准Claims字段:
- Issuer (iss): 签发者
- Subject (sub): 主题
- Audience (aud): 接收方
- ExpiresAt (exp): 过期时间
- NotBefore (nbf): 生效时间
- IssuedAt (iat): 签发时间
- ID (jti): 令牌ID
注意事项:
- 密钥应妥善保管,建议从配置文件或环境变量读取
- 生产环境使用RS256等非对称算法更安全
- 令牌过期时间不宜过长,建议24小时内
- 密钥应足够复杂,避免使用弱密钥
Index ¶
- Variables
- type ILiteUtilJWT
- type ILiteUtilJWTClaims
- type JWTAlgorithm
- type MapClaims
- func (c MapClaims) GetAudience() []string
- func (c MapClaims) GetCustomClaims() map[string]interface{}
- func (c MapClaims) GetExpiresAt() *time.Time
- func (c MapClaims) GetIssuedAt() *time.Time
- func (c MapClaims) GetIssuer() string
- func (c MapClaims) GetNotBefore() *time.Time
- func (c MapClaims) GetSubject() string
- func (c MapClaims) SetCustomClaims(claims map[string]interface{})
- type StandardClaims
- func (c StandardClaims) GetAudience() []string
- func (c StandardClaims) GetCustomClaims() map[string]interface{}
- func (c StandardClaims) GetExpiresAt() *time.Time
- func (c StandardClaims) GetIssuedAt() *time.Time
- func (c StandardClaims) GetIssuer() string
- func (c StandardClaims) GetNotBefore() *time.Time
- func (c StandardClaims) GetSubject() string
- func (c *StandardClaims) SetCustomClaims(claims map[string]interface{})
- type ValidateOption
- type ValidateOptions
Constants ¶
This section is empty.
Variables ¶
View Source
var JWT = defaultJWT
Functions ¶
This section is empty.
Types ¶
type ILiteUtilJWT ¶
type ILiteUtilJWT interface {
// JWT 生成方法
GenerateHS256Token(claims ILiteUtilJWTClaims, secretKey []byte) (string, error)
GenerateHS512Token(claims ILiteUtilJWTClaims, secretKey []byte) (string, error)
GenerateRS256Token(claims ILiteUtilJWTClaims, privateKey *rsa.PrivateKey) (string, error)
GenerateES256Token(claims ILiteUtilJWTClaims, privateKey *ecdsa.PrivateKey) (string, error)
GenerateToken(claims ILiteUtilJWTClaims, algorithm JWTAlgorithm, secretKey []byte,
rsaPrivateKey *rsa.PrivateKey, ecdsaPrivateKey *ecdsa.PrivateKey) (string, error)
// JWT 解析方法
ParseHS256Token(token string, secretKey []byte) (MapClaims, error)
ParseHS512Token(token string, secretKey []byte) (MapClaims, error)
ParseRS256Token(token string, publicKey *rsa.PublicKey) (MapClaims, error)
ParseES256Token(token string, publicKey *ecdsa.PublicKey) (MapClaims, error)
ParseToken(token string, algorithm JWTAlgorithm, secretKey []byte,
rsaPublicKey *rsa.PublicKey, ecdsaPublicKey *ecdsa.PublicKey) (MapClaims, error)
// JWT 验证方法
ValidateClaims(claims ILiteUtilJWTClaims, options ...ValidateOption) error
// 便捷方法
NewStandardClaims() *StandardClaims
NewMapClaims() MapClaims
SetExpiration(claims ILiteUtilJWTClaims, duration time.Duration)
SetIssuedAt(claims ILiteUtilJWTClaims, t time.Time)
SetNotBefore(claims ILiteUtilJWTClaims, t time.Time)
SetIssuer(claims ILiteUtilJWTClaims, issuer string)
SetSubject(claims ILiteUtilJWTClaims, subject string)
SetAudience(claims ILiteUtilJWTClaims, audience ...string)
AddCustomClaim(claims ILiteUtilJWTClaims, key string, value interface{})
}
ILiteUtilJWT JWT 工具接口
type ILiteUtilJWTClaims ¶
type ILiteUtilJWTClaims interface {
// GetExpiresAt 获取过期时间
GetExpiresAt() *time.Time
// GetIssuedAt 获取签发时间
GetIssuedAt() *time.Time
// GetNotBefore 获取生效时间
GetNotBefore() *time.Time
// GetIssuer 获取签发者
GetIssuer() string
// GetSubject 获取主题
GetSubject() string
// GetAudience 获取受众
GetAudience() []string
// GetCustomClaims 获取自定义声明
GetCustomClaims() map[string]interface{}
// SetCustomClaims 设置自定义声明
SetCustomClaims(claims map[string]interface{})
}
ILiteUtilJWTClaims JWT声明接口
type JWTAlgorithm ¶
type JWTAlgorithm string
JWTAlgorithm JWT签名算法类型
const ( // HS256 HMAC使用SHA-256 HS256 JWTAlgorithm = "HS256" // HS384 HMAC使用SHA-384 HS384 JWTAlgorithm = "HS384" // HS512 HMAC使用SHA-512 HS512 JWTAlgorithm = "HS512" // RS256 RSASSA-PKCS1-v1_5使用SHA-256 RS256 JWTAlgorithm = "RS256" // RS384 RSASSA-PKCS1-v1_5使用SHA-384 RS384 JWTAlgorithm = "RS384" // RS512 RSASSA-PKCS1-v1_5使用SHA-512 RS512 JWTAlgorithm = "RS512" // ES256 ECDSA使用P-256和SHA-256 ES256 JWTAlgorithm = "ES256" // ES384 ECDSA使用P-384和SHA-384 ES384 JWTAlgorithm = "ES384" // ES512 ECDSA使用P-521和SHA-512 ES512 JWTAlgorithm = "ES512" )
type MapClaims ¶
type MapClaims map[string]interface{}
MapClaims 映射形式的JWT声明,支持自定义字段
func (MapClaims) GetCustomClaims ¶
GetCustomClaims 获取自定义声明
func (MapClaims) SetCustomClaims ¶
SetCustomClaims 设置自定义声明
type StandardClaims ¶
type StandardClaims struct {
Audience []string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
ID string `json:"jti,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
Issuer string `json:"iss,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
Subject string `json:"sub,omitempty"`
}
StandardClaims 标准JWT声明
func (StandardClaims) GetCustomClaims ¶
func (c StandardClaims) GetCustomClaims() map[string]interface{}
GetCustomClaims 获取自定义声明(StandardClaims无自定义字段)
func (StandardClaims) GetExpiresAt ¶
func (c StandardClaims) GetExpiresAt() *time.Time
GetExpiresAt 获取过期时间
func (StandardClaims) GetIssuedAt ¶
func (c StandardClaims) GetIssuedAt() *time.Time
GetIssuedAt 获取签发时间
func (StandardClaims) GetNotBefore ¶
func (c StandardClaims) GetNotBefore() *time.Time
GetNotBefore 获取生效时间
func (*StandardClaims) SetCustomClaims ¶
func (c *StandardClaims) SetCustomClaims(claims map[string]interface{})
SetCustomClaims 设置自定义声明(StandardClaims不支持自定义字段)
type ValidateOption ¶
type ValidateOption func(*ValidateOptions)
ValidateOption JWT验证选项函数
func WithCurrentTime ¶
func WithCurrentTime(t time.Time) ValidateOption
WithCurrentTime 设置当前时间(用于测试)
Click to show internal directories.
Click to hide internal directories.