CSRF returns a middleware that enables CSRF protection via a sync token. The skipCheck parameter can be used to skip CSRF protection based on the request interface.
(authKey []byte, opts ...csrf.Option)
| 30 | // skipCheck parameter can be used to skip CSRF protection based on the request |
| 31 | // interface. |
| 32 | func CSRF(authKey []byte, opts ...csrf.Option) MiddlewareFunc { |
| 33 | return func(next http.Handler) http.Handler { |
| 34 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 35 | if canSkipCSRFMiddleware(r) { |
| 36 | next.ServeHTTP(w, r) |
| 37 | return |
| 38 | } |
| 39 | defaultOptions := []csrf.Option{ |
| 40 | csrf.SameSite(csrf.SameSiteLaxMode), |
| 41 | csrf.Secure(r.URL.Scheme == "https"), |
| 42 | csrf.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 43 | // In some cases we do want to execute the CSRF middleware, so that a CSRF token is set |
| 44 | // but we don't want to enforce CSRF token validation. |
| 45 | if canSkipCSRFCheck(r) { |
| 46 | next.ServeHTTP(w, r) |
| 47 | return |
| 48 | } |
| 49 | webhandlers.Error(w, r, errInvalidCSRFToken.New()) |
| 50 | })), |
| 51 | } |
| 52 | handler := csrf.Protect(authKey, append(defaultOptions, opts...)...)(next) |
| 53 | handler.ServeHTTP(w, r) |
| 54 | }) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | func canSkipCSRFMiddleware(r *http.Request) bool { |
| 59 | authVal := r.Header.Get("Authorization") |