package token import ( "github.com/golang-jwt/jwt/v4" "github.com/google/uuid" "time" ) func (t *token) JwtSign(userId uint64, platform 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 /*-------------------------------*/ // uid: (Custom ID) 用户ID c := claims{ userId, jwt.RegisteredClaims{ Issuer: "BvBeJ", Subject: platform, Audience: jwt.ClaimStrings(t.domain), ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)), NotBefore: jwt.NewNumericDate(time.Now()), IssuedAt: jwt.NewNumericDate(time.Now()), ID: uuid.New().String(), }, } tokenString, err = jwt.NewWithClaims(jwt.SigningMethodHS256, c).SignedString([]byte(t.secret)) return } func (t *token) JwtParse(tokenString string) (*claims, error) { tokenClaims, err := jwt.ParseWithClaims(tokenString, &claims{}, func(token *jwt.Token) (any, error) { return []byte(t.secret), nil }) if tokenClaims != nil { if c, ok := tokenClaims.Claims.(*claims); ok && tokenClaims.Valid { return c, nil } } return nil, err }