ToMiddleware converts CSRFConfig to middleware or returns an error for invalid configuration
()
| 124 | |
| 125 | // ToMiddleware converts CSRFConfig to middleware or returns an error for invalid configuration |
| 126 | func (config CSRFConfig) ToMiddleware() (echo.MiddlewareFunc, error) { |
| 127 | // Defaults |
| 128 | if config.Skipper == nil { |
| 129 | config.Skipper = DefaultCSRFConfig.Skipper |
| 130 | } |
| 131 | if config.TokenLength == 0 { |
| 132 | config.TokenLength = DefaultCSRFConfig.TokenLength |
| 133 | } |
| 134 | if config.Generator == nil { |
| 135 | config.Generator = createRandomStringGenerator(config.TokenLength) |
| 136 | } |
| 137 | if config.TokenLookup == "" { |
| 138 | config.TokenLookup = DefaultCSRFConfig.TokenLookup |
| 139 | } |
| 140 | if config.ContextKey == "" { |
| 141 | config.ContextKey = DefaultCSRFConfig.ContextKey |
| 142 | } |
| 143 | if config.CookieName == "" { |
| 144 | config.CookieName = DefaultCSRFConfig.CookieName |
| 145 | } |
| 146 | if config.CookieMaxAge == 0 { |
| 147 | config.CookieMaxAge = DefaultCSRFConfig.CookieMaxAge |
| 148 | } |
| 149 | if config.CookieSameSite == http.SameSiteNoneMode { |
| 150 | config.CookieSecure = true |
| 151 | } |
| 152 | if len(config.TrustedOrigins) > 0 { |
| 153 | if err := validateOrigins(config.TrustedOrigins, "trusted origin"); err != nil { |
| 154 | return nil, err |
| 155 | } |
| 156 | config.TrustedOrigins = append([]string(nil), config.TrustedOrigins...) |
| 157 | } |
| 158 | |
| 159 | extractors, cErr := createExtractors(config.TokenLookup, 1) |
| 160 | if cErr != nil { |
| 161 | return nil, cErr |
| 162 | } |
| 163 | |
| 164 | return func(next echo.HandlerFunc) echo.HandlerFunc { |
| 165 | return func(c *echo.Context) error { |
| 166 | if config.Skipper(c) { |
| 167 | return next(c) |
| 168 | } |
| 169 | |
| 170 | // use the `Sec-Fetch-Site` header as part of a modern approach to CSRF protection |
| 171 | allow, err := config.checkSecFetchSiteRequest(c) |
| 172 | if err != nil { |
| 173 | return err |
| 174 | } |
| 175 | if allow { |
| 176 | return next(c) |
| 177 | } |
| 178 | |
| 179 | // Fallback to legacy token based CSRF protection |
| 180 | |
| 181 | token := "" |
| 182 | if k, err := c.Cookie(config.CookieName); err != nil { |
| 183 | token = config.Generator() // Generate token |