jwt.go 894 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package common
  2. import (
  3. "AIT/global"
  4. "AIT/models"
  5. "github.com/golang-jwt/jwt"
  6. "time"
  7. )
  8. var SigningKey = []byte(global.Config.Jwt.SigningKey)
  9. const TokenExpireDuration = time.Hour * 2
  10. type Claims struct {
  11. models.User
  12. Username string `json:"username"`
  13. jwt.StandardClaims
  14. }
  15. // GenerateToke 生成Token
  16. func GenerateToke(user models.User) (string, error) {
  17. expirationTime := time.Now().Add(TokenExpireDuration)
  18. user.Password = ""
  19. claims := Claims{
  20. user, user.UserName, jwt.StandardClaims{
  21. ExpiresAt: expirationTime.Unix(),
  22. Issuer: user.UserName,
  23. },
  24. }
  25. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  26. return token.SignedString(SigningKey)
  27. }
  28. // VerifyToken 验证Token
  29. func VerifyToken(tokenString string) error {
  30. _, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
  31. return SigningKey, nil
  32. })
  33. return err
  34. }