token_jwt.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package token
  2. import (
  3. "github.com/golang-jwt/jwt/v4"
  4. "github.com/google/uuid"
  5. "time"
  6. )
  7. func (t *token) JwtSign(userId uint64, platform string, expireDuration time.Duration) (tokenString string, err error) {
  8. // The token content.
  9. // iss: (Issuer)签发者
  10. // iat: (Issued At)签发时间,用Unix时间戳表示
  11. // exp: (Expiration Time)过期时间,用Unix时间戳表示
  12. // aud: (Audience)接收该JWT的一方
  13. // sub: (Subject)该JWT的主题
  14. // nbf: (Not Before)不要早于这个时间
  15. // jti: (JWT ID)用于标识JWT的唯一ID
  16. /*-------------------------------*/
  17. // uid: (Custom ID) 用户ID
  18. c := claims{
  19. userId,
  20. jwt.RegisteredClaims{
  21. Issuer: "BvBeJ",
  22. Subject: platform,
  23. Audience: jwt.ClaimStrings{t.domain},
  24. ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
  25. NotBefore: jwt.NewNumericDate(time.Now()),
  26. IssuedAt: jwt.NewNumericDate(time.Now()),
  27. ID: uuid.New().String(),
  28. },
  29. }
  30. tokenString, err = jwt.NewWithClaims(jwt.SigningMethodHS256, c).SignedString([]byte(t.secret))
  31. return
  32. }
  33. func (t *token) JwtParse(tokenString string) (*claims, error) {
  34. tokenClaims, err := jwt.ParseWithClaims(tokenString, &claims{}, func(token *jwt.Token) (any, error) {
  35. return []byte(t.secret), nil
  36. })
  37. if tokenClaims != nil {
  38. if c, ok := tokenClaims.Claims.(*claims); ok && tokenClaims.Valid {
  39. return c, nil
  40. }
  41. }
  42. return nil, err
  43. }