https://github.com/flamego/csrf
Package csrf is a middleware that generates and validates CSRF tokens for Flamego
https://github.com/flamego/csrf
csrf flamego go lsif-enabled middleware
Last synced: 4 months ago
JSON representation
Package csrf is a middleware that generates and validates CSRF tokens for Flamego
- Host: GitHub
- URL: https://github.com/flamego/csrf
- Owner: flamego
- License: mit
- Created: 2021-07-31T09:39:49.000Z (almost 5 years ago)
- Default Branch: main
- Last Pushed: 2024-12-31T16:45:16.000Z (over 1 year ago)
- Last Synced: 2024-12-31T17:28:26.680Z (over 1 year ago)
- Topics: csrf, flamego, go, lsif-enabled, middleware
- Language: Go
- Homepage:
- Size: 96.7 KB
- Stars: 7
- Watchers: 3
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# csrf
[](https://github.com/flamego/csrf/actions?query=workflow%3AGo)
[](https://pkg.go.dev/github.com/flamego/csrf?tab=doc)
Package csrf is a middleware that generates and validates CSRF tokens for [Flamego](https://github.com/flamego/flamego).
## Installation
```zsh
go get github.com/flamego/csrf
```
## Getting started
```html
Submit
```
```go
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](https://flamego.dev/middleware/csrf.html).
- Please [file an issue](https://github.com/flamego/flamego/issues) or [start a discussion](https://github.com/flamego/flamego/discussions) on the [flamego/flamego](https://github.com/flamego/flamego) repository.
## License
This project is under the MIT License. See the [LICENSE](LICENSE) file for the full license text.