token.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package middleware
  2. import (
  3. "github.com/golang-jwt/jwt"
  4. "iot_manager_service/config"
  5. "time"
  6. )
  7. const (
  8. Authorization = "Authorization"
  9. Audience = "audience"
  10. Issuer = "issuser"
  11. )
  12. var EmptyKeyFunc = func(t *jwt.Token) (interface{}, error) { return []byte(config.Instance().Server.TokenSign), nil }
  13. type Claims struct {
  14. jwt.StandardClaims
  15. TenantId string `json:"tenant_id"`
  16. UserId int `json:"user_id"`
  17. RoleId int `json:"role_id"`
  18. UserName string `json:"user_name"`
  19. Random string `json:"random"`
  20. }
  21. func GetAccessToken(userId, roleId int, tenantId string, userName string, random string) (string, error) {
  22. jwtToken := Claims{StandardClaims: jwt.StandardClaims{
  23. Audience: Audience,
  24. Issuer: Issuer,
  25. ExpiresAt: time.Now().Add(2 * time.Hour).Unix(),
  26. NotBefore: time.Now().Unix(),
  27. },
  28. UserId: userId,
  29. TenantId: tenantId,
  30. RoleId: roleId,
  31. UserName: userName,
  32. Random: random,
  33. }
  34. claims := jwt.NewWithClaims(jwt.SigningMethodHS512, jwtToken)
  35. return claims.SignedString([]byte(config.Instance().Server.TokenSign))
  36. }
  37. func ParseAccessToken(authorization string) *Claims {
  38. token, err := jwt.ParseWithClaims(authorization, &Claims{}, EmptyKeyFunc)
  39. if err != nil {
  40. return nil
  41. }
  42. claims, ok := token.Claims.(*Claims)
  43. if !ok {
  44. return nil
  45. }
  46. return claims
  47. }