用于 Go 的 CSRF 防护中间件。
nosurf is an HTTP package for Go
that helps you prevent Cross-Site Request Forgery attacks.
It acts like a middleware and therefore
is compatible with basically any Go HTTP application.
Even though CSRF is a prominent vulnerability, Go's web-related package infrastructure mostly consists of micro-frameworks that neither do implement CSRF checks, nor should they.
nosurf solves this problem by providing a CSRFHandler
that wraps your http.Handler and checks for CSRF attacks
on every non-safe (non-GET/HEAD/OPTIONS/TRACE) method.
nosurf requires Go 1.1 or later.
http.Handler (frameworks, your own handlers, etc.)
and acts like one itself.HTTP 400? No problem.…
In some cases the CSRF token may be send through a non standard way, e.g. a body or request is a JSON encoded message with one of the fields being a token.
In such case the handler(path) should be excluded from an automatic verification by using one of the exemption methods:
func (h *CSRFHandler) ExemptFunc(fn func(r *http.Request) bool)
func (h *CSRFHandler) ExemptGlob(pattern string)
func (h *CSRFHandler) ExemptGlobs(patterns ...string)
func (h *CSRFHandler) ExemptPath(path string)
func (h *CSRFHandler) ExemptPaths(paths ...string)
func (h *CSRFHandler) ExemptRegexp(re interface{})
func (h *CSRFHandler) ExemptRegexps(res ...interface{})
Later on, the token must be verified by manually getting the token from the cookie
and providing the token sent in body through: VerifyToken(tkn, tkn2 string) bool.
Example:
func HandleJson(w http.ResponseWriter, r *http.Request) {
d := struct{
X,Y int
Tkn string
}{}
json.Unmarshal(ioutil.ReadAll(r.Body), &d)
if !nosurf.VerifyToken(nosurf.Token(r), d.Tkn) {
http.Errorf(w, "CSRF token incorrect", http.StatusBadRequest)
return
}
// do smth cool
}
暂无开放 Issues,或尚未同步最近议题。