session

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 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 by setting MaxAge=-1. ClearCookie 通过 MaxAge=-1 删除 cookie。

func ReadCookie

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

ReadCookie returns the cookie value or empty string. ReadCookie 返回 cookie 值或空字符串。

func SetCSRFCookie

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

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

func SetRefreshCookie

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

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

func ValidateDoubleSubmit

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

ValidateDoubleSubmit checks CSRF double-submit token match. ValidateDoubleSubmit 校验 CSRF 双提交 token 是否一致。

Types

type CookieConfig

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

CookieConfig controls cookie attributes for auth tokens. CookieConfig 控制认证 cookie 的属性。

Set Name/Path/SameSite/Secure according to your deployment. 请按部署环境设置 Name/Path/SameSite/Secure。

func DefaultCookieConfig

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

DefaultCookieConfig returns a cookie config derived from the request scheme. DefaultCookieConfig 返回基于请求协议的 cookie 配置。 It treats TLS as secure. X-Forwarded-Proto is only trusted when the direct peer is in TrustedProxies. 它将 TLS 视为安全连接;仅当直接对端命中 TrustedProxies 时才信任 X-Forwarded-Proto。

type CookieTrustOptions

type CookieTrustOptions struct {
	TrustedProxies []netip.Prefix
}

CookieTrustOptions controls when forwarded proto headers may be trusted. CookieTrustOptions 控制何时可以信任转发协议头。

Jump to

Keyboard shortcuts

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