Files
VLoop/backend/internal/auth/jwt.go
huanghaosheng e3ee3eee2f
Some checks failed
CI/CD / Deploy (push) Failing after 5s
chore: 完善 jwt 相关部分注释
2026-10-13 11:03:52 +08:00

158 lines
4.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// internal/auth/jwt.go
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"sync"
"time"
"github.com/golang-jwt/jwt/v5"
)
// MinSecretBytes 是 HS256 签名密钥要求的最小字节长度(256 bit).
// 注意:这是"下限护栏", 用于拦截空值/占位符/短口令这类部署事故,
// 不能替代真正的随机熵, 可用 `openssl rand -hex 32` 生成.
const MinSecretBytes = 32
var (
// ErrSecretNotConfigured 表示 main 未调用 Configure.调用方应将其
// 视为服务端配置错误(HTTP 500), 而非客户端凭证错误(HTTP 401).
ErrSecretNotConfigured = errors.New("auth: JWT secret is not configured (call auth.Configure at startup)")
ErrSecretEmpty = errors.New("auth: JWT secret is empty")
ErrAccessTTLInvalid = errors.New("auth: AccessTokenTTL must be > 0")
secretMu sync.RWMutex
secretKey []byte
accessTTL time.Duration
)
// Options 是令牌签发策略, 由 main 从 config 装载后一次性注入.
// 用结构体而非多个位置参数, 后续新增 refresh TTL / issuer / 轮换密钥时不用改动函数签名.
type Options struct {
Secret string
AccessTokenTTL time.Duration
}
// Configure 设置 JWT 签名密钥与访问令牌有效期.必须在签发/校验任何 token
// 之前调用一次, 通常由 main 在加载配置后立即调用.
//
// 密钥按原始字节使用, 不做任何派生或编码变换(保证升级不失效既有 token).
func Configure(opts Options) error {
if opts.Secret == "" {
return ErrSecretEmpty
}
if len(opts.Secret) < MinSecretBytes {
return fmt.Errorf("auth: JWT secret too short: %d bytes, need >= %d", len(opts.Secret), MinSecretBytes)
}
if opts.AccessTokenTTL <= 0 {
return ErrAccessTTLInvalid
}
secretMu.Lock()
secretKey = []byte(opts.Secret)
accessTTL = opts.AccessTokenTTL
secretMu.Unlock()
return nil
}
// currentAccessTTL 返回已配置的访问令牌有效期.
func currentAccessTTL() time.Duration {
secretMu.RLock()
defer secretMu.RUnlock()
return accessTTL
}
// Fingerprint 返回密钥的不可逆指纹(sha256 前 8 个 hex 字符).
// 仅用于跨实例/跨进程核对"API 与 Worker 是否使用同一密钥", 不泄露密钥本身.
func Fingerprint() string {
secretMu.RLock()
defer secretMu.RUnlock()
if len(secretKey) == 0 {
return "unconfigured"
}
sum := sha256.Sum256(secretKey)
return hex.EncodeToString(sum[:])[:8]
}
// secret 返回已配置的密钥;未配置时返回 ErrSecretNotConfigured.
func secret() ([]byte, error) {
secretMu.RLock()
defer secretMu.RUnlock()
if len(secretKey) == 0 {
return nil, ErrSecretNotConfigured
}
return secretKey, nil
}
type Claims struct {
AccountID uint `json:"account_id"`
Username string `json:"username"`
jwt.RegisteredClaims
}
func GenerateToken(accountID uint, username string) (string, error) {
key, err := secret()
if err != nil {
return "", err
}
now := time.Now()
claims := Claims{
AccountID: accountID,
Username: username,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(currentAccessTTL())),
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(key)
}
func GenerateRefreshToken(accountID uint) (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func ParseToken(tokenString string) (*Claims, error) {
// 先取密钥:这样即使 token 本身畸形(keyfunc 不会被调用),
// "密钥未配置"也能稳定地以 ErrSecretNotConfigured 返回.
key, err := secret()
if err != nil {
return nil, err
}
token, err := jwt.ParseWithClaims(
tokenString,
&Claims{},
func(token *jwt.Token) (interface{}, error) {
if token.Method == nil || token.Method.Alg() != jwt.SigningMethodHS256.Alg() {
return nil, errors.New("unexpected signing method")
}
return key, nil
},
// 双保险:拒绝 HS256 之外的一切算法(含 alg=none 类攻击).
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
)
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, jwt.ErrTokenInvalidClaims
}
return claims, nil
}