csrf

GitHub Workflow Status Codecov GoDoc Sourcegraph

Package csrf is a middleware that generates and validates CSRF tokens for Flamego.

Installation

The minimum requirement of Go is 1.16.

  1. go get github.com/flamego/csrf

Getting started

  1. <!-- templates/protected.tmpl -->
  2. <form action="/protected" method="POST">
  3. <input type="hidden" name="_csrf" value="{{.CSRFToken}}">
  4. <button>Submit</button>
  5. </form>
  1. package main
  2. import (
  3. "net/http"
  4. "github.com/flamego/csrf"
  5. "github.com/flamego/flamego"
  6. "github.com/flamego/session"
  7. "github.com/flamego/template"
  8. )
  9. func main() {
  10. f := flamego.Classic()
  11. f.Use(template.Templater())
  12. f.Use(session.Sessioner())
  13. f.Use(csrf.Csrfer())
  14. // Simulate the authentication of a session. If the "userID" exists,
  15. // then redirect to a form that requires CSRF protection.
  16. f.Get("/", func(c flamego.Context, s session.Session) {
  17. if s.Get("userID") == nil {
  18. c.Redirect("/login")
  19. return
  20. }
  21. c.Redirect("/protected")
  22. })
  23. // Set uid for the session.
  24. f.Get("/login", func(c flamego.Context, s session.Session) {
  25. s.Set("userID", 123)
  26. c.Redirect("/")
  27. })
  28. // Render a protected form by passing a CSRF token using x.Token().
  29. f.Get("/protected", func(c flamego.Context, s session.Session, x csrf.CSRF, t template.Template, data template.Data) {
  30. if s.Get("userID") == nil {
  31. c.Redirect("/login", http.StatusUnauthorized)
  32. return
  33. }
  34. // Pass token to the protected template.
  35. data["CSRFToken"] = x.Token()
  36. t.HTML(http.StatusOK, "protected")
  37. })
  38. // Apply CSRF validation to route.
  39. f.Post("/protected", csrf.Validate, func(c flamego.Context, s session.Session, t template.Template) {
  40. if s.Get("userID") != nil {
  41. c.ResponseWriter().Write([]byte("You submitted with a valid CSRF token"))
  42. return
  43. }
  44. c.Redirect("/login", http.StatusUnauthorized)
  45. })
  46. f.Run()
  47. }

Getting help

License

This project is under the MIT License. See the LICENSE file for the full license text.