base-golang/pkg/token/token_jwt.go

44 lines
1.3 KiB
Go
Raw Permalink Normal View History

2024-07-23 10:23:43 +08:00
package token
import (
"github.com/golang-jwt/jwt/v4"
"time"
)
func (t *token) JwtSign(userId, subject string, expireDuration time.Duration) (tokenString string, err error) {
// The token content.
// iss: Issuer签发者
// iat: Issued At签发时间用Unix时间戳表示
// exp: Expiration Time过期时间用Unix时间戳表示
// aud: Audience接收该JWT的一方
// sub: Subject该JWT的主题
// nbf: Not Before不要早于这个时间
// jti: JWT ID用于标识JWT的唯一ID
c := &jwt.RegisteredClaims{
Issuer: "BvBeJ",
Subject: subject,
Audience: jwt.ClaimStrings(t.domain),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
NotBefore: jwt.NewNumericDate(time.Now()),
IssuedAt: jwt.NewNumericDate(time.Now()),
ID: userId,
}
tokenString, err = jwt.NewWithClaims(jwt.SigningMethodHS256, c).SignedString([]byte(t.secret))
return
}
func (t *token) JwtParse(tokenString string) (*jwt.RegisteredClaims, error) {
tokenClaims, err := jwt.ParseWithClaims(tokenString, &jwt.RegisteredClaims{}, func(token *jwt.Token) (any, error) {
return []byte(t.secret), nil
})
if tokenClaims != nil {
if c, ok := tokenClaims.Claims.(*jwt.RegisteredClaims); ok && tokenClaims.Valid {
return c, nil
}
}
return nil, err
}