csrf

The csrf middleware generates and validates CSRF tokens for Flame instances, it relies on the session middleware.

You can read source code of this middleware on GitHubcsrf - 图1open in new window and API documentation on pkg.go.devcsrf - 图2open in new window.

Installation

The minimum requirement of Go is 1.16.

  1. go get github.com/flamego/csrf

Usage examples

WARNING

Examples included in this section is to demonstrate the usage of the csrf middleware, by no means illustrates the idiomatic or even correct way of doing user authentication.

The csrf.Csrfercsrf - 图3open in new window works out-of-the-box with an optional csrf.Optionscsrf - 图4open in new window, and the csrf.Validatecsrf - 图5open in new window should be used to guard routes that needs CSRF validation:

  • main.go
  • templates/protected.tmpl
  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. }
  1. <form action="/protected" method="POST">
  2. <input type="hidden" name="_csrf" value="{{.CSRFToken}}">
  3. <button>Submit</button>
  4. </form>