3 changed files with 39 additions and 5 deletions
@ -0,0 +1,30 @@ |
|||||
|
package middleware |
||||
|
|
||||
|
import ( |
||||
|
"net/http" |
||||
|
"strings" |
||||
|
|
||||
|
"github.com/gorilla/csrf" |
||||
|
) |
||||
|
|
||||
|
// CSRFExposeToken sets a readable cookie with the per-request masked CSRF token on safe methods.
|
||||
|
func CSRFExposeToken(next http.Handler) http.Handler { |
||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
||||
|
switch r.Method { |
||||
|
case http.MethodGet, http.MethodHead, http.MethodOptions: |
||||
|
token := csrf.Token(r) |
||||
|
if token != "" { |
||||
|
secure := r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https") |
||||
|
http.SetCookie(w, &http.Cookie{ |
||||
|
Name: "XSRF-TOKEN-VALUE", |
||||
|
Value: token, |
||||
|
Path: "/", |
||||
|
HttpOnly: false, |
||||
|
Secure: secure, |
||||
|
SameSite: http.SameSiteLaxMode, |
||||
|
}) |
||||
|
} |
||||
|
} |
||||
|
next.ServeHTTP(w, r) |
||||
|
}) |
||||
|
} |
||||
Loading…
Reference in new issue