Csrf
Package csrf is a middleware that generates and validates CSRF tokens for Flamego
Install / Use
/learn @flamego/CsrfREADME
csrf
Package csrf is a middleware that generates and validates CSRF tokens for Flamego.
Installation
go get github.com/flamego/csrf
Getting started
<!-- 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()
}
Getting help
- Read documentation and examples.
- Please file an issue or start a discussion on the flamego/flamego repository.
License
This project is under the MIT License. See the LICENSE file for the full license text.
Related Skills
node-connect
342.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.7kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
342.0kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
84.7kCommit, push, and open a PR
