跨域请求攻击(CSRF)
中间件 csrf 用于为 Macaron 实例 生成和验证 CSRF 令牌。
下载安装
go get github.com/go-macaron/csrf使用示例
想要使用该中间件,您必须同时使用 session 中间件。
package main
import (
"github.com/go-macaron/csrf"
"github.com/go-macaron/session"
"gopkg.in/macaron.v1"
)
func main() {
m := macaron.Classic()
m.Use(macaron.Renderer())
m.Use(session.Sessioner())
m.Use(csrf.Csrfer())
// 模拟验证过程,判断 session 中是否存在 uid 数据。
// 若不存在,则跳转到一个生成 CSRF 的页面。
m.Get("/", func(ctx *macaron.Context, sess session.Store) {
if sess.Get("uid") == nil {
ctx.Redirect("/login")
return
}
ctx.Redirect("/protected")
})
// 设置 session 中的 uid 数据。
m.Get("/login", func(ctx *macaron.Context, sess session.Store) {
sess.Set("uid", 123456)
ctx.Redirect("/")
})
// 渲染一个需要验证的表单,并传递 CSRF 令牌到表单中。
m.Get("/protected", func(ctx *macaron.Context, sess session.Store, x csrf.CSRF) {
if sess.Get("uid") == nil {
ctx.Redirect("/login", 401)
return
}
ctx.Data["csrf_token"] = x.GetToken()
ctx.HTML(200, "protected")
})
// 验证 CSRF 令牌。
m.Post("/protected", csrf.Validate, func(ctx *macaron.Context, sess session.Store) {
if sess.Get("uid") != nil {
ctx.RenderData(200, []byte("You submitted a valid token"))
return
}
ctx.Redirect("/login", 401)
})
m.Run()
}自定义选项
该服务允许接受一个参数来进行自定义选项(csrf.Options):
Last updated
Was this helpful?