jwt.go 828 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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("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()),
  16. ExpiresAt: int64(time.Now().Unix() + 90*24*60*60),
  17. Issuer: "hongze_admin",
  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. }