token.go 980 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "iot_manager_service/util/common"
  5. "iot_manager_service/util/token"
  6. "net/http"
  7. "strings"
  8. )
  9. // 验证token令牌的中间件
  10. func AuthMiddleware() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. //如果包含路径/login则放行,其余的都要进行token认证
  13. if strings.Contains(c.Request.RequestURI, "/login") ||
  14. strings.Contains(c.Request.RequestURI, "/websocket") ||
  15. strings.Contains(c.Request.RequestURI, "/getpublickey") {
  16. c.Next()
  17. return
  18. }
  19. // 从请求头中获取token
  20. tokenString := c.GetHeader("Authorization")
  21. if tokenString == "" {
  22. c.JSON(http.StatusOK, common.ParamsInvalidResponse("Token不能为空", nil))
  23. c.Abort()
  24. return
  25. }
  26. //解析token
  27. _, err := token.JwtClaims.ParseJwtToken(tokenString)
  28. //过期或者无效
  29. if err != nil {
  30. c.JSON(http.StatusUnauthorized, common.StatusUnauthorized("Token失效", nil))
  31. c.Abort()
  32. return
  33. }
  34. c.Next()
  35. }
  36. }