Go 的 CSRF 中间件:nosurf

jopen 10年前

nosurf 是 Go 语言的一个 CSRF 跨站请求伪造(Cross Site Request Forgery) 中间件,可嵌入到 net/http 中使用,可方便与 Gorilla 和 Martini 框架结合使用。

特性:

  • Supports any http.Handler (frameworks, your own handlers, etc.) and acts like one itself.
  • Allows exempting specific endpoints from CSRF checks by an exact URL, a glob, or a regular expression.
  • Allows specifying your own failure handler. Want to present the hacker with an ASCII middle finger instead of the plain old HTTP 400? No problem.
  • Has no dependencies outside the Go standard library.

示例代码:

package main    import (      "fmt"      "github.com/justinas/nosurf"      "html/template"      "net/http"  )    var templateString string = `  <!doctype html>  <html>  <body>  {{ if .name }}  <p>Your name: {{ .name }}</p>  {{ end }}  <form action="/" method="POST">  <input type="text" name="name">    <!-- Try removing this or changing its value       and see what happens -->  <input type="hidden" name="csrf_token" value="{{ .token }}">  <input type="submit" value="Send">  </form>  </body>  </html>  `  var templ = template.Must(template.New("t1").Parse(templateString))    func myFunc(w http.ResponseWriter, r *http.Request) {      context := make(map[string]string)      context["token"] = nosurf.Token(r)      if r.Method == "POST" {          context["name"] = r.FormValue("name")      }        templ.Execute(w, context)  }    func main() {      myHandler := http.HandlerFunc(myFunc)      fmt.Println("Listening on http://127.0.0.1:8000/")      http.ListenAndServe(":8000", nosurf.New(myHandler))  }

项目主页:http://www.open-open.com/lib/view/home/1385008718875