Package csrf is a middleware that generates and validates CSRF tokens for Flamego.
The minimum requirement of Go is 1.18.
go get github.com/flamego/csrf
<!-- templates/protected.tmpl -->
<form action="/protected" method="POST">
<input type="hidden" name="_csrf" value="{{.CSRFToken}}">
<button>Submit</button>
</form>
package main
import (
"net/http"
"github.com/flamego/csrf"
"github.com/flamego/flamego"
"github.com/flamego/session"
"github.com/flamego/template"
)
func main() {
f := flamego.Classic()
f.Use(template.Templater())
f.Use(session.Sessioner())
f.Use(csrf.Csrfer())
// Simulate the authentication of a session. If the "userID" exists,
// then redirect to a form that requires CSRF protection.
f.Get("/", func(c flamego.Context, s session.Session) {
if s.Get("userID") == nil {
c.Redirect("/login")
return
}
c.Redirect("/protected")
})
// Set uid for the session.
f.Get("/login", func(c flamego.Context, s session.Session) {
s.Set("userID", 123)
c.Redirect("/")
})
// Render a protected form by passing a CSRF token using x.Token().
f.Get("/protected", func(c flamego.Context, s session.Session, x csrf.CSRF, t template.Template, data template.Data) {
if s.Get("userID") == nil {
c.Redirect("/login", http.StatusUnauthorized)
return
}
// Pass token to the protected template.
data["CSRFToken"] = x.Token()
t.HTML(http.StatusOK, "protected")
})
// Apply CSRF validation to route.
f.Post("/protected", csrf.Validate, func(c flamego.Context, s session.Session, t template.Template) {
if s.Get("userID") != nil {
c.ResponseWriter().Write([]byte("You submitted with a valid CSRF token"))
return
}
c.Redirect("/login", http.StatusUnauthorized)
})
f.Run()
}
- Read documentation and examples.
- Please file an issue or start a discussion on the flamego/flamego repository.
This project is under the MIT License. See the LICENSE file for the full license text.