gorilla/csrf

[BUG] Middleware doesn't work with Chi

romanian-bag-void opened this issue · 1 comments

Is there an existing issue for this?

  • I have searched the existing issues

Current Behavior

Looks like a bug to me, but I hope I'm not missing something. I don't know if this is a Chi-related issue, or gorilla-csrf issue.

I'm trying to use chi with the CSRF middleware, but for some reason, despite it being easy to access the token, on protected routes they don't appear. I understand how the whole CSRF process should work usually, and have read the docs, but I don't seem to be able to create protected routes. In my particular case, I want to get the CSRF token as a JSON attribute, but I think that is redundant in this case.

Expected Behavior

CSRF-protected routes should require the token in some form to be accessible and give a 403 Forbidden error if they are not provided the token.

Steps To Reproduce

Create a default middleware, apply it to the router, apply it to individual routes, doesn't work. Doesn't work on groups either.

Anything else?

The code:

`

func main() {router := chi.NewRouter()

CSRFMiddleware := csrf.Protect([]byte("32-byte-long-auth-key")) // change 32-bla to something random

router.Use(middleware.Logger)	

router.Group(func(r chi.Router) {
	r.Use(CSRFMiddleware)

	router.Get("/get-token", func(w http.ResponseWriter, r *http.Request) {
		render.JSON(w, r,  csrf.Token(r))
	})

	router.Get("/1", func(w http.ResponseWriter, r *http.Request) {
		render.JSON(w, r, "no middleware!")
	})

	router.With(CSRFMiddleware).Get("/2", func(w http.ResponseWriter, r *http.Request) {
		render.JSON(w, r, "with middleware!")
	})
})
	// Routes outside a group
	router.Get("/3", func(w http.ResponseWriter, r *http.Request) {
	render.JSON(w, r, "no group, no middleware!")
})

	router.With(CSRFMiddleware).Get("/4", func(w http.ResponseWriter, r *http.Request) {
	render.JSON(w, r, "no group, with middleware!")
})

http.ListenAndServe(":3000", router)}

`

Hi @romanian-bag-void,
This does not seem to be a bug. In csrf.go#L244 you can see that the "safe" methods (GET, HEAD, ...) are not inspected. If you change the method of one of your protected endpoints to "POST" then you will get a 403 response as you expect.