1234567891011121314151617181920212223242526272829303132333435363738 |
- package middleware
- import (
- "github.com/gin-gonic/gin"
- "iot_manager_service/util/common"
- "iot_manager_service/util/token"
- "net/http"
- "strings"
- )
- // 验证token令牌的中间件
- func AuthMiddleware() gin.HandlerFunc {
- return func(c *gin.Context) {
- //如果包含路径/login则放行,其余的都要进行token认证
- if strings.Contains(c.Request.RequestURI, "/login") ||
- strings.Contains(c.Request.RequestURI, "/websocket") ||
- strings.Contains(c.Request.RequestURI, "/getpublickey") {
- c.Next()
- return
- }
- // 从请求头中获取token
- tokenString := c.GetHeader("Authorization")
- if tokenString == "" {
- c.JSON(http.StatusOK, common.ParamsInvalidResponse("Token不能为空", nil))
- c.Abort()
- return
- }
- //解析token
- _, err := token.JwtClaims.ParseJwtToken(tokenString)
- //过期或者无效
- if err != nil {
- c.JSON(http.StatusUnauthorized, common.StatusUnauthorized("Token失效", nil))
- c.Abort()
- return
- }
- c.Next()
- }
- }
|