Documentation
¶
Index ¶
Constants ¶
const CSRF_TOKEN_MIXIN = "HGEGY#G$tewdRwvweRftrsTcHyr"
CSRF_TOKEN_MIXIN is a static app-wide mix-in used to augment weak or empty secrets. It is not a secret unless sourced from configuration or environment.
const DefaultPackagedExpiry = 15 * time.Minute
DefaultPackagedExpiry is the default TTL for packaged tokens when Options.ExpiresAt is not set. Deterministic rule: issue time (UTC) + 15 minutes.
Variables ¶
This section is empty.
Functions ¶
func TokenGenerate ¶
TokenGenerate generates a CSRF token from the provided secret. Optional opts[0] can customize binding and expiry behavior. This function always returns a packaged token in the form "<bcrypt-hash>:<expiresUnix>" and binds the expiry into the hash input as "|exp:<expiresUnix>" to prevent tampering. If ExpiresAt is zero, the expiry defaults to now (UTC) + DefaultPackagedExpiry.
func TokenValidate ¶
TokenValidate validates a packaged CSRF token produced by TokenGenerate.
This function internally unpacks the token format used by the generator. The function will:
- Unpackage the token and parse the embedded expiry timestamp.
- Reject the token if it is expired relative to time.Now().UTC().
- Rebuild the plaintext using the provided secret plus any request-bound attributes enabled via Options (e.g., BindIP, BindUserAgent, BindPath, BindMethod).
- Compare the bcrypt hash against the rebuilt plaintext (truncated to 72 bytes).
If opts is omitted or ExpiresAt is zero, a default expiry of now + DefaultPackagedExpiry is assumed for rebuilding the plaintext, keeping generation and validation consistent.
Types ¶
type Options ¶
type Options struct {
// Request is the incoming HTTP request whose attributes can be bound into the token.
// If nil, no request attributes are used regardless of the Bind* flags.
Request *http.Request
// BindIP, when true, mixes the client IP (X-Forwarded-For first, then X-Real-IP,
// then RemoteAddr) into the token. This reduces token reuse from different IPs.
BindIP bool
// BindUserAgent, when true, mixes the request's User-Agent header into the token.
// This helps constrain reuse across different clients/browsers.
BindUserAgent bool
// BindPath, when true, mixes the request URL path into the token, constraining
// a token to a specific endpoint/path.
BindPath bool
// BindMethod, when true, mixes the HTTP method (e.g., POST) into the token.
// Useful if you want tokens to be valid only for a given method.
BindMethod bool
// ExpiresAt sets the absolute expiry (UTC) for packaged tokens. If zero, the generator
// uses a deterministic default of now (UTC) + DefaultPackagedExpiry.
ExpiresAt time.Time
}
Options allows optional request binding for CSRF token generation/validation, and lets you set an absolute expiry for packaged tokens. All fields are optional. If Request is nil or a Bind* flag is false, that attribute is not used. ExpiresAt controls the expiry timestamp embedded into packaged tokens.