CSRF

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

Usage

  1. 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.

Example Configuration that reads token from Cookie

  1. middleware.CSRFWithConfig(middleware.CSRFConfig{
  2. TokenLookup: "cookie:_csrf",
  3. CookiePath: "/",
  4. CookieDomain: "example.com",
  5. CookieSecure: true,
  6. CookieHTTPOnly: true,
  7. CookieSameSite: http.SameSiteStrictMode,
  8. })

Accessing CSRF Token

Server-side

CSRF token can be accessed from Echo#Context using ContextKey and passed to the 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. // - "cookie:<name>"
  15. TokenLookup string `json:"token_lookup"`
  16. // Context key to store generated CSRF token into context.
  17. // Optional. Default value "csrf".
  18. ContextKey string `json:"context_key"`
  19. // Name of the CSRF cookie. This cookie will store CSRF token.
  20. // Optional. Default value "_csrf".
  21. CookieName string `json:"cookie_name"`
  22. // Domain of the CSRF cookie.
  23. // Optional. Default value none.
  24. CookieDomain string `json:"cookie_domain"`
  25. // Path of the CSRF cookie.
  26. // Optional. Default value none.
  27. CookiePath string `json:"cookie_path"`
  28. // Max age (in seconds) of the CSRF cookie.
  29. // Optional. Default value 86400 (24hr).
  30. CookieMaxAge int `json:"cookie_max_age"`
  31. // Indicates if CSRF cookie is secure.
  32. // Optional. Default value false.
  33. CookieSecure bool `json:"cookie_secure"`
  34. // Indicates if CSRF cookie is HTTP only.
  35. // Optional. Default value false.
  36. CookieHTTPOnly bool `json:"cookie_http_only"`
  37. }

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. }