an updated and hopefully faster version of the ST Toolbox
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

30 lines
766 B

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