Code Monkey home page Code Monkey logo

Comments (5)

gonboy avatar gonboy commented on May 20, 2024 2

maybe you can use belown method

func xxAuthorizator func(userID string, c *gin.Context) bool {
    claims := jwt.ExtractClaims(c)
    //.... get token and do your things
}

from gin-jwt.

arrwhidev avatar arrwhidev commented on May 20, 2024

Hi @philippecarle, or anyone else, did you find an elegant solution to this?

I also would like to pass a different Authorizator function for different groups, ideally without creating multiple middlewares.

Thanks!

from gin-jwt.

 avatar commented on May 20, 2024

@arrwhidev you can create a single middleware and switch between its parameter:

func GroupAuthorizator(group string) gin.HandlerFunc {
	return func(c *gin.Context) {
		switch group {
		case "product":
			usr, _ := c.Get("id")
			fmt.Println(usr.(*models.User).UserName)
			c.Next()
                        return
		default:
			jwt.Unauthorized(c, http.StatusForbidden, jwt.HTTPStatusMessageFunc(jwt.ErrForbidden, c))
		}
	}
}

And then, create your gin group router like this:

t := &ProductRouter{}
tR := r.Group("/product")
tR.Use(jwt.MiddlewareFunc(), GroupAuthorizator("product"))
tR.GET("/", t.GetProduct)

from gin-jwt.

tomriddle1234 avatar tomriddle1234 commented on May 20, 2024

@alcmoraes, could you be more detailed ? how to distinguish normal user, admin user, guest user?

usr, _ := c.Get("id")
fmt.Println(usr.(*models.User).UserName)
c.Next()
return

Could you explain these lines ?

from gin-jwt.

tomriddle1234 avatar tomriddle1234 commented on May 20, 2024

Currently I hacked in the gin-jwt source code, like this, to by pass the authenticator function for normal users, so I achieved 3 roles, normal user, admin, and guest without login

// NormalMiddlewareFunc makes GinJWTMiddleware implement the Middleware interface by pass the admin identity check
func (mw *GinJWTMiddleware) NormalMiddlewareFunc() gin.HandlerFunc {
	return func(c *gin.Context) {
		mw.normalMiddlewareImpl(c)
	}
}

func (mw *GinJWTMiddleware) normalMiddlewareImpl(c *gin.Context) {
	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)
	}

	c.Next()
}

Then I used such middleware function like,

	knowledgeRoutes := router.Group("/data")
	{
		knowledgeRoutes.Use(jwtMiddleware.NormalMiddlewareFunc())
		{
			//these fetch functions record statistics
			knowledgeRoutes.GET("/getknowledgelist",  getKnowledgeListHandler)
			knowledgeRoutes.GET("/getallknowledge", getAllKnowledgeHandler)
			knowledgeRoutes.GET("/getknowledge/:name", getKnowledgeByNameHandler)
			knowledgeRoutes.GET("/getknowledgelogo/:name", getKnowledgeLogoHandler)
			knowledgeRoutes.POST("/searchknowledge/:keyword", searchKnowledgeKeywordHandler)
		}

	}

from gin-jwt.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.