gin-jwt
gin-jwt copied to clipboard
Url whitelist without token check
// 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()
}
}
I will take it.