session

package
v0.1.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package session provides cookie helpers for auth flows. Package session 提供认证流程的 cookie 辅助函数。

Usage (Double-submit CSRF) / 用法(双提交 CSRF):

csrf := uuid.NewString()
SetCSRFCookie(w, csrf, exp, CookieConfig{Name: DefaultCSRFCookieName, Path: "/"})
// Client sends header: X-CSRF-Token: <csrf>
ok := ValidateDoubleSubmit(r, DefaultCSRFCookieName, DefaultCSRFHeaderName)

Index

Constants

View Source
const (
	DefaultRefreshCookieName = "refresh"
	DefaultCSRFCookieName    = "csrf"
	DefaultCSRFHeaderName    = "X-CSRF-Token"
)

Variables

This section is empty.

Functions

func ClearCookie

func ClearCookie(w http.ResponseWriter, cfg CookieConfig)

ClearCookie removes a cookie. ClearCookie 删除 cookie。

func ReadCookie

func ReadCookie(r *http.Request, name string) string

ReadCookie returns the cookie value. Missing cookies return an empty string. ReadCookie 返回 cookie 值。 缺失 cookie 时返回空字符串。

func SetCSRFCookie

func SetCSRFCookie(w http.ResponseWriter, token string, exp time.Time, cfg CookieConfig)

SetCSRFCookie writes the CSRF token cookie. SetCSRFCookie 写入 CSRF token cookie。

func SetRefreshCookie

func SetRefreshCookie(w http.ResponseWriter, token string, exp time.Time, cfg CookieConfig)

SetRefreshCookie writes the refresh token cookie. SetRefreshCookie 写入 refresh token cookie。

func ValidateDoubleSubmit

func ValidateDoubleSubmit(r *http.Request, cookieName, headerName string) bool

ValidateDoubleSubmit compares the CSRF cookie and header. ValidateDoubleSubmit 比较 CSRF cookie 与 header。

Types

type CookieConfig

type CookieConfig struct {
	Name        string
	Path        string
	Domain      string
	Secure      bool
	SameSite    http.SameSite
	SessionOnly bool
}

CookieConfig configures auth cookies. CookieConfig 配置认证 cookie。

func DefaultCookieConfig

func DefaultCookieConfig(r *http.Request, opts CookieTrustOptions) CookieConfig

DefaultCookieConfig derives Secure and SameSite from r. TLS is always trusted. X-Forwarded-Proto is trusted only for TrustedProxies. DefaultCookieConfig 从 r 推导 Secure 与 SameSite。 TLS 总是可信;X-Forwarded-Proto 仅对 TrustedProxies 生效。

type CookieTrustOptions

type CookieTrustOptions struct {
	TrustedProxies []netip.Prefix
}

CookieTrustOptions configures forwarded-proto trust. CookieTrustOptions 配置转发协议头信任边界。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL