buaazp / fasthttprouter

A high performance fasthttp request router that scales well
http://godoc.org/github.com/buaazp/fasthttprouter
BSD 3-Clause "New" or "Revised" License
876 stars 91 forks source link

JWT middleware support #36

Open basilex opened 6 years ago

basilex commented 6 years ago

It whould be nice to have an implementation of JWT auth middleware like an existing basic auth. Thanx!

ChadTaljaardt commented 6 years ago

I would like this too!

DarkDrim commented 6 years ago

Example of auth middleware for fasthttp & fasthttprouter

type Middleware func(h fasthttp.RequestHandler) fasthttp.RequestHandler
type AuthFunc func(ctx *fasthttp.RequestCtx) bool
func NewAuthMiddleware(authFunc AuthFunc) Middleware {
    return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
        return func(ctx *fasthttp.RequestCtx) {
            result, err := authFunc(ctx)
            if result {
                h(ctx)
            } else {
                ctx.Response.SetStatusCode(fasthttp.StatusUnauthorized)
            }
        }
    }
}

func AuthCheck(ctx *fasthttp.RequestCtx) (bool, error) {
    return false; // for example ;)
}

// router
authMiddleware := middleware.NewAuthMiddleware(security.AuthCheck)
...
router.GET("/protected", authMiddleware(handlers.ProtectedHandler))
rafgugi commented 4 years ago

i think middleware should not too coupled in the router. you should implement your middleware in your appliaction yourself because it depends on how the security of your appliaction.