JWT middleware?


#1

Hopefully this should be simple but I’ve done some poking around and can’t figure it out. I’m using JWT for various routes like this:

r.Use(middleware.JWT([]byte("secret")))

I have a route that the user needs to access regardless of the JWT status. If I use the middleware then it it doesn’t let them access the route without a valid token. If I don’t use the middleware then the “user” is never set in the context and there is no way detect if user IsLoggedIn(). Suggestions? Thanks in advance.


#2

Hello,

As per the documentation (Guide > Routing > Group) you can use Group for that, so that you only associate certain middleware with a group of routes but not all.

If you really want to do it at the route level, you can do that easily. What all middleware’s return is a MiddlewareFunc, see https://github.com/labstack/echo/blob/master/middleware/jwt.go#L85

If we look at the definition of MiddlewareFunc, we see it’s a function that consumes a HandlerFunc and returns a HandlerFunc, so you could simply use something like:

e.GET("/foo", middleware.JWT([]byte("secret")(func(c echo.Context) error {
	return c.String(http.StatusOK, "/users/:id")
}))

However if we take a closer look at GET() definition we can see that it actually accepts optional arguments in the form of MiddlewareFunc’s :slight_smile: so the above can be written as simple as:

e.GET("/foo", func(c echo.Context) error {
	return c.String(http.StatusOK, "/users/:id")
}, middleware.JWT([]byte("secret"))

(which for what is worth, is doing exactly what was outlined earlier: https://github.com/labstack/echo/blob/master/echo.go#L476

So there are plenty of ways to achieve what you need, with the granularity you need.

Cheers!
Alex