token_jwt.go 1.3 KB

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