This commit is contained in:
toom1996
2026-08-31 19:59:56 +08:00
parent a325e438be
commit f4f6e02e3c
14 changed files with 594 additions and 20 deletions

View File

@ -44,6 +44,21 @@ func NewManager(secret string, expireHours int) *Manager {
// 将来接入登录时恢复:构造 jwtlib.MapClaims{"uid","username","email","exp"},
// 再用 jwtlib.NewWithClaims(jwtlib.SigningMethodHS256, claims).SignedString(m.secret) 签名即可。
// Generate 签发令牌(登录成功后调用)。
//
// 构造与 Parse 对称的 Claims(uid / username / email / exp),用 HS256 签名。
// exp 由 Manager 的 expire 决定(默认 7 天,见 NewManager)。
func (m *Manager) Generate(userID uint32, username, email string) (string, error) {
claims := jwtlib.MapClaims{
"uid": float64(userID),
"username": username,
"email": email,
"exp": time.Now().Add(m.expire).Unix(),
}
token := jwtlib.NewWithClaims(jwtlib.SigningMethodHS256, claims)
return token.SignedString(m.secret)
}
// Parse 校验并解析令牌。
func (m *Manager) Parse(tokenStr string) (*Claims, error) {
token, err := jwtlib.Parse(tokenStr, func(t *jwtlib.Token) (any, error) {