jwt.go 835 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package utils
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/beego/beego/v2/core/logs"
  6. "github.com/dgrijalva/jwt-go"
  7. )
  8. var (
  9. KEY = []byte("5McoGDMb5y")
  10. )
  11. func GenToken(account string) string {
  12. token := jwt.New(jwt.SigningMethodHS256)
  13. token.Claims = &jwt.StandardClaims{
  14. NotBefore: int64(time.Now().Unix()) - int64(1*time.Second),
  15. ExpiresAt: int64(time.Now().Unix() + 60*24*60*60),
  16. Issuer: "eta_mini_crm",
  17. Subject: account,
  18. }
  19. ss, err := token.SignedString(KEY)
  20. if err != nil {
  21. logs.Error(err)
  22. return ""
  23. }
  24. return ss
  25. }
  26. // 校验token
  27. func CheckToken(account, token string) bool {
  28. t, err := jwt.Parse(token, func(*jwt.Token) (interface{}, error) {
  29. return KEY, nil
  30. })
  31. if err != nil {
  32. fmt.Println(err.Error())
  33. return false
  34. }
  35. if account != t.Claims.(jwt.MapClaims)["sub"] {
  36. return false
  37. }
  38. return t.Valid
  39. }