justinas / nosurf

CSRF protection middleware for Go.

Home Page:http://godoc.org/github.com/justinas/nosurf

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Filtering out safe methods and excluded paths

inmylo opened this issue · comments

Nosurf excludes safe methods (like GET) and paths (using ExemptPaths) when there is no need to check CSRF token. It's good, but..

In handler.go you have a function ServeHTTP, and after every request even if you are not interested in checking a token, you still do:

  • addNosurfContext(r)
  • w.Header().Add("Vary", "Cookie")
  • tokenCookie, err := r.Cookie(CookieName)
  • realToken = b64decode(tokenCookie.Value)
  • if len(realToken) != tokenLength { ...

.. and this all is useless because then you do:

if sContains(safeMethods, r.Method) || h.IsExempt(r) {
    // short-circuit with a success for safe methods
    h.handleSuccess(w, r)
    return
}

I offer you to move this check to the top of the ServeHTTP function as much as possible, so nosurf can avoid doing useless operations. Performance will be increased

Hi,

This is basically all intended behavior, as Exempt...() exempts paths from CSRF checking, but not from regenerating the token in case it does not exist at all or is of invalid format (see previous discussion).

Not regenerating a cookie would mean you would be unable to POST from an exempted or "safe" route to a protected route, unless there already exists a valid token cookie.

@Imilo Closing this for now, hopefully my answer was helpful. Feel free to submit any further inquiries.