Any plans on a csrf middleware?
robvdl opened this issue · 6 comments
How about adding csrf token generation and middleware support to contrib, I notice there is this currently:
https://github.com/tommy351/gin-csrf
However, that requires tommmy351/gin-sessions rather than the sessions from gin-gonic/contrib/sessions, it would make sense to have a csrf library that worked with gin-gonic/contrib/sessions instead.
I also notice that gin-csrf seems to implement the csrf code from scratch, there is also gorilla/csrf that could have maybe been used as a foundation maybe? but gin-csrf does not appear to be using that.
Later I found a fork of this library github.com/utrack/gin-csrf that has been adapted to work with gin-contrib sessions.
However I have found another library nosurf which seems to be much more mature than gin-csrf.
+1
@robvdl
There is already https://github.com/gin-gonic/nosurf
Simplified example
func main() {
r := gin.Default()
csrf := nosurf.New(r)
csrf.SetFailureHandler(http.HandlerFunc(csrfFailHandler))
http.ListenAndServe(":8000", csrf)
}
func csrfFailHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s\n", nosurf.Reason(r))
}
func DisplayForm(c *gin.Context) {
// in your form
// <input type="hidden" name="csrf_token" value="{{ csrf_token }}">
c.HTML(200, "foo.html", pongo2.Context{"csrf_token": nosurf.Token(c.Request)})
}
Yep, that's exactly what I have already been doing, I found that out not long after I wrote this issue, so I am not sure a csrf middleware is really needed in contrib, should we close this issue?
should we close this issue?
Yes, we should instead improve readme/docs of https://github.com/gin-gonic/nosurf
Please note, at this moment this fork is far behind justinas/nosurf
.