File tree 2 files changed +38
-2
lines changed 2 files changed +38
-2
lines changed Original file line number Diff line number Diff line change @@ -61,7 +61,13 @@ type (
61
61
// Indicates SameSite mode of the CSRF cookie.
62
62
// Optional. Default value SameSiteDefaultMode.
63
63
CookieSameSite http.SameSite `yaml:"cookie_same_site"`
64
+
65
+ // ErrorHandler defines a function which is executed for returning custom errors.
66
+ ErrorHandler CSRFErrorHandler
64
67
}
68
+
69
+ // CSRFErrorHandler is a function which is executed for creating custom errors.
70
+ CSRFErrorHandler func (err error , c echo.Context ) error
65
71
)
66
72
67
73
// ErrCSRFInvalid is returned when CSRF check fails
@@ -154,8 +160,9 @@ func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
154
160
lastTokenErr = ErrCSRFInvalid
155
161
}
156
162
}
163
+ var finalErr error
157
164
if lastTokenErr != nil {
158
- return lastTokenErr
165
+ finalErr = lastTokenErr
159
166
} else if lastExtractorErr != nil {
160
167
// ugly part to preserve backwards compatible errors. someone could rely on them
161
168
if lastExtractorErr == errQueryExtractorValueMissing {
@@ -167,7 +174,14 @@ func CSRFWithConfig(config CSRFConfig) echo.MiddlewareFunc {
167
174
} else {
168
175
lastExtractorErr = echo .NewHTTPError (http .StatusBadRequest , lastExtractorErr .Error ())
169
176
}
170
- return lastExtractorErr
177
+ finalErr = lastExtractorErr
178
+ }
179
+
180
+ if finalErr != nil {
181
+ if config .ErrorHandler != nil {
182
+ return config .ErrorHandler (finalErr , c )
183
+ }
184
+ return finalErr
171
185
}
172
186
}
173
187
Original file line number Diff line number Diff line change @@ -358,3 +358,25 @@ func TestCSRFConfig_skipper(t *testing.T) {
358
358
})
359
359
}
360
360
}
361
+
362
+ func TestCSRFErrorHandling (t * testing.T ) {
363
+ cfg := CSRFConfig {
364
+ ErrorHandler : func (err error , c echo.Context ) error {
365
+ return echo .NewHTTPError (http .StatusTeapot , "error_handler_executed" )
366
+ },
367
+ }
368
+
369
+ e := echo .New ()
370
+ e .POST ("/" , func (c echo.Context ) error {
371
+ return c .String (http .StatusNotImplemented , "should not end up here" )
372
+ })
373
+
374
+ e .Use (CSRFWithConfig (cfg ))
375
+
376
+ req := httptest .NewRequest (http .MethodPost , "/" , nil )
377
+ res := httptest .NewRecorder ()
378
+ e .ServeHTTP (res , req )
379
+
380
+ assert .Equal (t , http .StatusTeapot , res .Code )
381
+ assert .Equal (t , "{\" message\" :\" error_handler_executed\" }\n " , res .Body .String ())
382
+ }
You can’t perform that action at this time.
0 commit comments