gin-jwt icon indicating copy to clipboard operation
gin-jwt copied to clipboard

Url whitelist without token check

Open hahait opened this issue 4 years ago • 1 comments

// On the premise of registering MW.MiddlewareFunc() as global middleware, partial url token - free authentication is implemented

type GinJWTMiddleware struct {
    ……
    // Add the following property to the structure to define the URL whitelist
    // example:  WhiteUrlList []string{"/login", "/dashboard/overview", "/user/info?id=8"}
    WhiteUrlList []string
}

// Add the following method to verify that the url currently requested is in the URL whitelist

func (mw *GinJWTMiddleware) checkWhiteUrlList(c_url string) bool {
        for _, wul := range mw.WhiteUrlList {
                if c_url == wul {
                        return true
                }
        }
        return false
}

func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
    // Pass the url of the current request to checkWhiteUrlList() to determine whether it is in the whitelist;If it is, the request is passed on to other handlers for processing
    if mw.checkWhiteUrlList(c.Request.URL.RequestURI()) {
        c.Next()
    } else {
        claims, err := mw.GetClaimsFromJWT(c)
        if err != nil {
            mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(err, c))
            return
        }

        if claims["exp"] == nil {
            mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrMissingExpField, c))
            return
        }

        if _, ok := claims["exp"].(float64); !ok {
            mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrWrongFormatOfExp, c))
            return
        }

        if int64(claims["exp"].(float64)) < mw.TimeFunc().Unix() {
            mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
            return
        }

        c.Set("JWT_PAYLOAD", claims)
        identity := mw.IdentityHandler(c)

        if identity != nil {
            c.Set(mw.IdentityKey, identity)
        }

        if !mw.Authorizator(identity, c) {
            mw.unauthorized(c, http.StatusForbidden, mw.HTTPStatusMessageFunc(ErrForbidden, c))
            return
        }

        c.Next()
    }
}

hahait avatar Jul 27 '20 09:07 hahait

I will take it.

appleboy avatar Oct 10 '20 09:10 appleboy