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
- func ClearCookie(w http.ResponseWriter, cfg CookieConfig)
- func ReadCookie(r *http.Request, name string) string
- func SetCSRFCookie(w http.ResponseWriter, token string, exp time.Time, cfg CookieConfig)
- func SetRefreshCookie(w http.ResponseWriter, token string, exp time.Time, cfg CookieConfig)
- func ValidateDoubleSubmit(r *http.Request, cookieName, headerName string) bool
- type CookieConfig
- type CookieTrustOptions
Constants ¶
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 ¶
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。
Types ¶
type CookieConfig ¶
type CookieConfig struct {
Name string
Path string
Domain string
Secure bool
SameSite http.SameSite
}
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 ¶
CookieTrustOptions controls when forwarded proto headers may be trusted. CookieTrustOptions 控制何时可以信任转发协议头。