jwt.go 825 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package utils
  2. import (
  3. "fmt"
  4. "github.com/beego/beego/v2/core/logs"
  5. "github.com/dgrijalva/jwt-go"
  6. "time"
  7. )
  8. var (
  9. KEY = []byte("5Mb5Gdmb5x")
  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()),
  16. ExpiresAt: int64(time.Now().Unix() + 90*24*60*60),
  17. Issuer: "hongze_mfyx",
  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. }