44 lines
1.3 KiB
Go
44 lines
1.3 KiB
Go
|
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
|
|||
|
}
|