base-golang/pkg/token/token_jwt.go
2024-07-23 10:23:43 +08:00

44 lines
1.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.

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
}