Documentation
¶
Overview ¶
Package httpauth provides non-invasive, standard net/http transport utilities for authentication workflows in go-modular-auth.
It operates purely on standard *http.Request and http.ResponseWriter interfaces, without imposing any router, routing abstractions, or external framework dependencies. It is fully compatible with stdlib net/http, Fuego, Gin, Fiber (via adaptors), Chi, Echo, and any other Go web framework.
Key capabilities include:
- Secure session cookie management with OWASP-recommended defaults (HttpOnly, SameSite=Lax, Secure).
- Cascading token extraction across Cookies, Authorization Bearer headers, and URL query parameters.
- Robust client IP and User-Agent resolution behind reverse proxies (X-Forwarded-For, X-Real-IP, RemoteAddr).
- Type-safe request context propagation for entity.Session and entity.User using unexported context keys.
Index ¶
- Constants
- Variables
- func ClearSessionCookie(w http.ResponseWriter, opts ...CookieOption)
- func ExtractToken(r *http.Request, opts ...ExtractOption) (string, error)
- func GetClientIP(r *http.Request) string
- func GetUserAgent(r *http.Request) string
- func SessionDataFromContext(ctx context.Context) (*dto.SessionData, bool)
- func SessionFromContext(ctx context.Context) (*entity.Session, bool)
- func SetSessionCookie(w http.ResponseWriter, token string, expires time.Time, opts ...CookieOption)
- func UserFromContext(ctx context.Context) (*entity.User, bool)
- func WithSession(ctx context.Context, session *entity.Session) context.Context
- func WithSessionData(ctx context.Context, data *dto.SessionData) context.Context
- func WithUser(ctx context.Context, user *entity.User) context.Context
- type CookieConfig
- type CookieOption
- func WithCookieName(name string) CookieOption
- func WithDomain(domain string) CookieOption
- func WithHTTPOnly(httpOnly bool) CookieOption
- func WithPartitioned(partitioned bool) CookieOption
- func WithPath(path string) CookieOption
- func WithSameSite(sameSite http.SameSite) CookieOption
- func WithSecure(secure bool) CookieOption
- type ExtractConfig
- type ExtractOption
- type TokenSource
Constants ¶
const ( DefaultSessionCookieName = "auth_session" DefaultCookiePath = "/" )
Default cookie configuration constants.
const ( DefaultExtractCookieName = "auth_session" DefaultExtractHeaderName = "Authorization" DefaultExtractHeaderPrefix = "Bearer " DefaultExtractQueryParam = "token" )
Default extraction settings.
Variables ¶
var ( // ErrTokenNotFound is returned when no session or bearer token is found in any configured source. ErrTokenNotFound = errors.New("httpauth: token not found") // ErrNilRequest is returned when an HTTP operation is called with a nil *http.Request. ErrNilRequest = errors.New("httpauth: nil http request") // ErrNilResponseWriter is returned when a cookie operation is called with a nil http.ResponseWriter. ErrNilResponseWriter = errors.New("httpauth: nil http response writer") )
Functions ¶
func ClearSessionCookie ¶
func ClearSessionCookie(w http.ResponseWriter, opts ...CookieOption)
ClearSessionCookie clears the active session cookie by setting its value to empty and MaxAge to -1.
func ExtractToken ¶
func ExtractToken(r *http.Request, opts ...ExtractOption) (string, error)
ExtractToken inspects the given HTTP request and extracts an authentication token using the configured cascading strategy (default: Cookie -> Authorization: Bearer -> Query Param). Returns the raw token string, or ErrTokenNotFound if no token was located.
func GetClientIP ¶
GetClientIP extracts and validates the real client IP address from an HTTP request. It follows the resolution hierarchy:
- X-Forwarded-For header (first valid IP in a comma-separated list)
- X-Real-IP header
- RemoteAddr (stripping host port if present)
Returns a canonical string representation of the IP, or empty string if no valid IP is detected.
func GetUserAgent ¶
GetUserAgent returns the trimmed User-Agent header value from the HTTP request. Returns an empty string if the request is nil or the header is not provided.
func SessionDataFromContext ¶
func SessionDataFromContext(ctx context.Context) (*dto.SessionData, bool)
SessionDataFromContext reconstructs a *dto.SessionData if either a session or user is present in the context. Returns (nil, false) if neither is found.
func SessionFromContext ¶
SessionFromContext extracts the authenticated *entity.Session from the context. Returns (nil, false) if no session was stored or if the value is not a valid *entity.Session.
func SetSessionCookie ¶
func SetSessionCookie(w http.ResponseWriter, token string, expires time.Time, opts ...CookieOption)
SetSessionCookie sets a secure HTTP-only cookie with the provided session token and expiration. It applies safe defaults (HttpOnly, Secure, SameSite=Lax, Path="/") which can be customized via opts.
func UserFromContext ¶
UserFromContext extracts the authenticated *entity.User from the context. Returns (nil, false) if no user was stored or if the value is not a valid *entity.User.
func WithSession ¶
WithSession stores an authenticated *entity.Session into the context using a private key.
func WithSessionData ¶
WithSessionData injects both Session and User from a *dto.SessionData into the context.
Types ¶
type CookieConfig ¶
type CookieConfig struct {
// Name specifies the cookie name. Defaults to "auth_session".
Name string
// Path defines the URL path that must exist in the requested URL for the cookie to be sent. Defaults to "/".
Path string
// Domain specifies which hosts can receive the cookie. Defaults to empty (current host only).
Domain string
// Secure specifies whether the cookie should only be transmitted over HTTPS. Defaults to true.
Secure bool
// HTTPOnly specifies whether the cookie is inaccessible to client-side scripts. Defaults to true.
HTTPOnly bool
// SameSite controls cross-site request behavior. Defaults to http.SameSiteLaxMode.
SameSite http.SameSite
// Partitioned specifies whether the cookie should be stored using partitioned storage (CHIPS).
Partitioned bool
}
CookieConfig holds configurable attributes applied when emitting or clearing session cookies.
func DefaultCookieConfig ¶
func DefaultCookieConfig() CookieConfig
DefaultCookieConfig returns the production-safe default cookie settings.
type CookieOption ¶
type CookieOption func(*CookieConfig)
CookieOption represents a functional option for customizing cookie attributes.
func WithCookieName ¶
func WithCookieName(name string) CookieOption
WithCookieName overrides the session cookie name.
func WithDomain ¶
func WithDomain(domain string) CookieOption
WithDomain sets the Domain attribute on the session cookie.
func WithHTTPOnly ¶
func WithHTTPOnly(httpOnly bool) CookieOption
WithHTTPOnly controls whether the HttpOnly flag is enabled on the session cookie.
func WithPartitioned ¶
func WithPartitioned(partitioned bool) CookieOption
WithPartitioned controls the Partitioned attribute (CHIPS) on the session cookie.
func WithPath ¶
func WithPath(path string) CookieOption
WithPath sets the Path attribute on the session cookie.
func WithSameSite ¶
func WithSameSite(sameSite http.SameSite) CookieOption
WithSameSite sets the SameSite policy on the session cookie.
func WithSecure ¶
func WithSecure(secure bool) CookieOption
WithSecure controls whether the Secure flag is enabled on the session cookie.
type ExtractConfig ¶
type ExtractConfig struct {
// Sources defines the ordered search cascade.
Sources []TokenSource
// CookieName specifies the session cookie name to look up.
CookieName string
// HeaderName specifies the HTTP header name.
HeaderName string
// HeaderPrefix specifies the prefix preceding the token in the header.
HeaderPrefix string
// QueryParam specifies the URL query parameter name.
QueryParam string
}
ExtractConfig holds configurable strategies for extracting tokens from an HTTP request.
func DefaultExtractConfig ¶
func DefaultExtractConfig() ExtractConfig
DefaultExtractConfig returns the standard cascading token extraction settings (Cookie -> Bearer Header).
type ExtractOption ¶
type ExtractOption func(*ExtractConfig)
ExtractOption represents a functional option for customizing token extraction.
func WithExtractBearer ¶
func WithExtractBearer() ExtractOption
WithExtractBearer configures standard "Authorization: Bearer <token>" extraction.
func WithExtractCookie ¶
func WithExtractCookie(name string) ExtractOption
WithExtractCookie configures the cookie name to inspect during extraction.
func WithExtractHeader ¶
func WithExtractHeader(headerName, prefix string) ExtractOption
WithExtractHeader configures a custom header name and optional prefix.
func WithExtractQueryParam ¶
func WithExtractQueryParam(paramName string) ExtractOption
WithExtractQueryParam configures a query parameter name and activates SourceQuery in the search cascade.
func WithSources ¶
func WithSources(sources ...TokenSource) ExtractOption
WithSources explicitly overrides the extraction sources and their evaluation order.
type TokenSource ¶
type TokenSource int
TokenSource represents an extraction source for authentication tokens.
const ( // SourceCookie extracts tokens from HTTP request cookies. SourceCookie TokenSource = iota + 1 // SourceHeader extracts tokens from request HTTP headers (e.g., Authorization: Bearer). SourceHeader // SourceQuery extracts tokens from URL query parameters. SourceQuery )