fix(auth): set SameSite=None for viewer session cookie over HTTPS and update docs

This commit is contained in:
zwitschi committed 2026-08-16 09:45:58 +02:00
1 parent 85454610f4
commit 4fe09a0a3d
5 files changed
+69 -16

No files matched your search

+27 -8
View File
@@ -88,29 +88,48 @@ func CookieSecure(r *http.Request) bool {
return r.TLS != nil
}
// SetCookie writes the admin session cookie.
func SetCookie(w http.ResponseWriter, r *http.Request, cookieName, token string, expiresAt time.Time) {
// SameSiteForUserCookie returns the SameSite policy for the viewer session cookie.
// Over HTTPS it returns SameSite=None so the cookie is sent cross-site from the
// Workers-served SPA; over plain HTTP (local dev) it falls back to Lax.
func SameSiteForUserCookie(r *http.Request) http.SameSite {
if CookieSecure(r) {
return http.SameSiteNoneMode
}
return http.SameSiteLaxMode
}
// SetCookie writes a session cookie with the given SameSite policy.
// SameSite=None is only valid together with Secure, which is enforced here.
func SetCookie(w http.ResponseWriter, r *http.Request, cookieName, token string, expiresAt time.Time, sameSite http.SameSite) {
secure := CookieSecure(r)
if sameSite == http.SameSiteNoneMode {
secure = true
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: token,
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: CookieSecure(r),
SameSite: sameSite,
Secure: secure,
Expires: expiresAt,
MaxAge: int(time.Until(expiresAt).Seconds()),
})
}
// ClearCookie removes the admin session cookie.
func ClearCookie(w http.ResponseWriter, r *http.Request, cookieName string) {
// ClearCookie removes a session cookie with the given SameSite policy.
func ClearCookie(w http.ResponseWriter, r *http.Request, cookieName string, sameSite http.SameSite) {
secure := CookieSecure(r)
if sameSite == http.SameSiteNoneMode {
secure = true
}
http.SetCookie(w, &http.Cookie{
Name: cookieName,
Value: "",
Path: "/",
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
Secure: CookieSecure(r),
SameSite: sameSite,
Secure: secure,
Expires: time.Unix(0, 0),
MaxAge: -1,
})