CSRF Middleware

Cross-site request forgery, also known as one-click attack or session riding andabbreviated as CSRF (sometimes pronounced sea-surf) or XSRF, is a type of maliciousexploit of a website where unauthorized commands are transmitted from a user thatthe website trusts.

Usage

e.Use(middleware.CSRF())

Custom Configuration

Usage

  1. e := echo.New()
  2. e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
  3. TokenLookup: "header:X-XSRF-TOKEN",
  4. }))

Example above uses X-XSRF-TOKEN request header to extract CSRF token.

Accessing CSRF Token

Server-side

CSRF token can be accessed from Echo#Context using ContextKey and passed tothe client via template.

Client-side

CSRF token can be accessed from CSRF cookie.

Configuration

  1. CSRFConfig struct {
  2. // Skipper defines a function to skip middleware.
  3. Skipper Skipper
  4. // TokenLength is the length of the generated token.
  5. TokenLength uint8 `json:"token_length"`
  6. // Optional. Default value 32.
  7. // TokenLookup is a string in the form of "<source>:<key>" that is used
  8. // to extract token from the request.
  9. // Optional. Default value "header:X-CSRF-Token".
  10. // Possible values:
  11. // - "header:<name>"
  12. // - "form:<name>"
  13. // - "query:<name>"
  14. TokenLookup string `json:"token_lookup"`
  15. // Context key to store generated CSRF token into context.
  16. // Optional. Default value "csrf".
  17. ContextKey string `json:"context_key"`
  18. // Name of the CSRF cookie. This cookie will store CSRF token.
  19. // Optional. Default value "csrf".
  20. CookieName string `json:"cookie_name"`
  21. // Domain of the CSRF cookie.
  22. // Optional. Default value none.
  23. CookieDomain string `json:"cookie_domain"`
  24. // Path of the CSRF cookie.
  25. // Optional. Default value none.
  26. CookiePath string `json:"cookie_path"`
  27. // Max age (in seconds) of the CSRF cookie.
  28. // Optional. Default value 86400 (24hr).
  29. CookieMaxAge int `json:"cookie_max_age"`
  30. // Indicates if CSRF cookie is secure.
  31. // Optional. Default value false.
  32. CookieSecure bool `json:"cookie_secure"`
  33. // Indicates if CSRF cookie is HTTP only.
  34. // Optional. Default value false.
  35. CookieHTTPOnly bool `json:"cookie_http_only"`
  36. }

Default Configuration

  1. DefaultCSRFConfig = CSRFConfig{
  2. Skipper: DefaultSkipper,
  3. TokenLength: 32,
  4. TokenLookup: "header:" + echo.HeaderXCSRFToken,
  5. ContextKey: "csrf",
  6. CookieName: "_csrf",
  7. CookieMaxAge: 86400,
  8. }