jwt.go 739 B

1234567891011121314151617181920212223242526272829303132333435
  1. /*
  2. * 用户鉴权
  3. */
  4. package jwt
  5. import (
  6. "time"
  7. "github.com/golang-jwt/jwt/v4"
  8. )
  9. type JwtStruct struct {
  10. SecretKey string
  11. TimeOut int64
  12. }
  13. var UserJwt = &JwtStruct{
  14. SecretKey: "jianyuservice", //保持一致
  15. TimeOut: 600,
  16. }
  17. func (this *JwtStruct) GetToken(payloads map[string]interface{}) (string, error) {
  18. now := time.Now().Add(-10 * time.Second).Unix() //当前时间往前10s iat时间要在相应服务器时间之前 否则会报错Token used before issued
  19. claims := make(jwt.MapClaims)
  20. claims["exp"] = now + this.TimeOut
  21. claims["iat"] = now
  22. for k, v := range payloads {
  23. claims[k] = v
  24. }
  25. token := jwt.New(jwt.SigningMethodHS256)
  26. token.Claims = claims
  27. return token.SignedString([]byte(this.SecretKey))
  28. }