Cross-Site Request Forgery
Middleware csrf generates and validates CSRF tokens for Macaron Instances.

Installation

1
go get github.com/go-macaron/csrf
Copied!

Usage

To use this middleware, you have to register session first.
1
package main
2
3
import (
4
"github.com/go-macaron/csrf"
5
"github.com/go-macaron/session"
6
"gopkg.in/macaron.v1"
7
)
8
9
func main() {
10
m := macaron.Classic()
11
m.Use(macaron.Renderer())
12
m.Use(session.Sessioner())
13
m.Use(csrf.Csrfer())
14
15
// Simulate the authentication of a session.
16
// If uid exists redirect to a form that requires CSRF protection.
17
m.Get("/", func(ctx *macaron.Context, sess session.Store) {
18
if sess.Get("uid") == nil {
19
ctx.Redirect("/login")
20
return
21
}
22
ctx.Redirect("/protected")
23
})
24
25
// Set uid for the session.
26
m.Get("/login", func(ctx *macaron.Context, sess session.Store) {
27
sess.Set("uid", 123456)
28
ctx.Redirect("/")
29
})
30
31
// Render a protected form. Passing a csrf token by calling x.GetToken()
32
m.Get("/protected", func(ctx *macaron.Context, sess session.Store, x csrf.CSRF) {
33
if sess.Get("uid") == nil {
34
ctx.Redirect("/login", 401)
35
return
36
}
37
38
// Pass token to the protected template.
39
ctx.Data["csrf_token"] = x.GetToken()
40
ctx.HTML(200, "protected")
41
})
42
43
// Apply CSRF validation to route.
44
m.Post("/protected", csrf.Validate, func(ctx *macaron.Context, sess session.Store) {
45
if sess.Get("uid") != nil {
46
ctx.RenderData(200, []byte("You submitted a valid token"))
47
return
48
}
49
ctx.Redirect("/login", 401)
50
})
51
52
m.Run()
53
}
Copied!
1
<!-- templates/protected.tmpl -->
2
<form action="/protected" method="post">
3
<input type="hidden" name="_csrf" value="{{.csrf_token}}">
4
<button>Submit</button>
5
</form>
Copied!

Options

csrf.Csrfer comes with a variety of configuration options:
1
// ...
2
m.Use(csrf.Csrfer(csrf.Options{
3
// The global secret value used to generate Tokens. Default is a random string.
4
Secret: "mysecret",
5
// HTTP header used to set and get token. Default is "X-CSRFToken".
6
Header: "X-CSRFToken",
7
// Form value used to set and get token. Default is "_csrf".
8
Form: "_csrf",
9
// Cookie value used to set and get token. Default is "_csrf".
10
Cookie: "_csrf",
11
// Cookie path. Default is "/".
12
CookiePath: "/",
13
// Key used for getting the unique ID per user. Default is "uid".
14
SessionKey: "uid",
15
// If true, send token via header. Default is false.
16
SetHeader: false,
17
// If true, send token via cookie. Default is false.
18
SetCookie: false,
19
// Set the Secure flag to true on the cookie. Default is false.
20
Secure: false,
21
// Disallow Origin appear in request header. Default is false.
22
Origin: false,
23
// The function called when Validate fails. Default is a simple error print.
24
ErrorFunc: func(w http.ResponseWriter) {
25
http.Error(w, "Invalid csrf token.", http.StatusBadRequest)
26
},
27
}))
28
// ...
Copied!
Last modified 2yr ago
Copy link