[Beego] How to Configure XSRF filtering

Tadashi Shigeoka ·  Tue, July 2, 2019

This article introduces how to configure Cross-Site Request Forgery (XSRF) filtering in Beego.

Beego

Beego Official Documentation XSRF filtering

Following the official documentation XSRF filtering - beego should work without any issues.

Beego XSRF filtering Sample Code

EnableXSRF sample codes · Pull Request #1 · codenote-net/beego-sandbox

EnableXSRF = true

conf/app.conf

# XSRF
# https://beego.me/docs/mvc/controller/xsrf.md
EnableXSRF = true
XSRFKey = cgMZA17YOErrEquLO9vqHiU1f7slQJXUCx0GhHGK
XSRFExpire = 3600 # set cookie expire in 3600 seconds, default to 60 seconds if not specified

commits/6b27a25a063bd7cefebd9dcf889fd6d716bc1ffa

CLI verification

$ curl -X POST http://localhost:8080/
2019/07/02 21:32:59.903 [C] [panic.go:522]  the request url is  /
2019/07/02 21:32:59.903 [C] [panic.go:522]  Handler crashed with error '_xsrf' argument missing from POST
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/gos/go1.12.5/src/runtime/panic.go:522
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/pkgsets/go1.12.5/global/pkg/mod/github.com/astaxie/[email protected]/context/context.go:88
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/pkgsets/go1.12.5/global/pkg/mod/github.com/astaxie/[email protected]/context/context.go:172
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/pkgsets/go1.12.5/global/pkg/mod/github.com/astaxie/[email protected]/controller.go:671
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/pkgsets/go1.12.5/global/pkg/mod/github.com/astaxie/[email protected]/router.go:824
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/gos/go1.12.5/src/net/http/server.go:2774
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/gos/go1.12.5/src/net/http/server.go:1878
2019/07/02 21:32:59.903 [C] [panic.go:522]  /Users/shigeoka/.gvm/gos/go1.12.5/src/runtime/asm_amd64.s:1337
2019/07/02 21:32:59.904 [server.go:3010]  [HTTP] http: superfluous response.WriteHeader call from github.com/astaxie/beego/context.(*Response).WriteHeader (context.go:230)

EnableXSRF = false in Prepare() method

controllers/about.go

func (c *AboutController) Prepare() {
  c.EnableXSRF = false
}

commits/8a14a36c9627f9fddaefe57aff287e457af32fab

CLI verification

$ curl -X POST http://localhost:8080/about
Method Not Allowed
2019/07/02 22:02:19.048 [D] [server.go:2774]  |            ::1| 405 |    259.315µs|   match| POST     /about   r:/about

That’s all from the Gemba on understanding how to configure XSRF countermeasures in Beego.