jwt.go 848 B

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