智盟项目
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mw_auth_jwt.go 1.1 KiB

1 년 전
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package mw
  2. import (
  3. "applet/app/e"
  4. "applet/app/utils"
  5. "errors"
  6. "github.com/dgrijalva/jwt-go"
  7. "strings"
  8. "time"
  9. "github.com/gin-gonic/gin"
  10. )
  11. // AuthJWT is jwt middleware
  12. func AuthJWT(c *gin.Context) {
  13. //获取请求头中的Authorization
  14. authHeader := c.Request.Header.Get("Authorization")
  15. if authHeader == "" {
  16. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 不能为空"))
  17. return
  18. }
  19. //拆分Authorization字段获取token字符串
  20. parts := strings.SplitN(authHeader, " ", 2)
  21. if !(len(parts) == 2 && parts[0] == "Bearer") {
  22. e.OutErr(c, e.ERR_TOKEN_FORMAT, errors.New("token 格式不对"))
  23. return
  24. }
  25. //验证token字符串
  26. claim, err := utils.ParseToken(parts[1])
  27. if err != nil {
  28. v, _ := err.(*jwt.ValidationError)
  29. if v.Errors == jwt.ValidationErrorExpired {
  30. e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("token 过期已失效"))
  31. return
  32. }
  33. e.OutErr(c, e.ERR_UNAUTHORIZED, errors.New("token 验证失败"))
  34. return
  35. }
  36. //过期判断
  37. if time.Now().Unix() > claim.ExpiresAt {
  38. e.OutErr(c, e.ERR_TOKEN_EXPIRE, errors.New("token 过期已失效"))
  39. return
  40. }
  41. //设置上下文信息
  42. c.Set("master_id", claim.MasterId)
  43. c.Next()
  44. }