checkAuth.go 621 B

1234567891011121314151617181920212223242526272829
  1. package middleware
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "iot_manager_service/util"
  5. "net/http"
  6. "strings"
  7. )
  8. func CheckAuth() gin.HandlerFunc {
  9. return func(ctx *gin.Context) {
  10. //该路由下不校验token
  11. if strings.Contains(ctx.Request.RequestURI, "/login") {
  12. ctx.Next()
  13. return
  14. }
  15. authorization := ctx.GetHeader(Authorization)
  16. if authorization != "" {
  17. token := parseAccessToken(authorization)
  18. if token != nil {
  19. ctx.Set(Authorization, token)
  20. ctx.Next()
  21. }
  22. }
  23. ctx.JSON(http.StatusUnauthorized, util.NormalResponse(http.StatusUnauthorized, "token is invalid", nil))
  24. ctx.Abort()
  25. }
  26. }