Documentation ¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrCtxKey = contextKey{"csusrf.err"} TokCtxKey = contextKey{"csusrf.tok"} )
Functions ¶
func FromContext ¶
FromContext retrieves a value of type T from the provided context using a specified ctxKey.
The function attempts to extract the value associated with the given ctxKey from the context. If the value exists and is of type T, it is returned along with a true boolean. If the value does not exist or is of an incompatible type, the function returns a zero value of type T and false boolean indicating the absence or type mismatch of the context key.
Types ¶
type CookieOptions ¶
type CookieOptions struct { Name string Path string Domain string MaxAge int Secure bool HttpOnly bool SameSite http.SameSite }
func DefaultCookieOptions ¶
func DefaultCookieOptions() CookieOptions
DefaultCookieOptions returns the default CookieOptions for CSRF cookie.
This function provides default values for initializing a CookieOptions instance when setting up CSRF protection.
func (CookieOptions) Cookie ¶
func (c CookieOptions) Cookie() *http.Cookie
Cookie returns an HTTP cookie initialized with the settings specified in CookieOptions.
If the MaxAge is greater than 0, the function sets the Expires field based on the current time and the specified MaxAge. This allows the CSRF cookie to expire after the specified duration.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
func NewManager ¶
func NewManager(secret []byte, opts ...ManagerOption) *Manager
NewManager returns a new Manager with the specified options.
func (*Manager) GenerateRandomBytes ¶
GenerateRandomBytes generates cryptographically secure random bytes.
func (*Manager) GenerateToken ¶
GenerateToken creates a new CSRF token for the given session.
It generates a random byte slice, encodes it using base64, and combines it with the provided sessionID. The resulting message is then hashed using HMAC SHA-256. The final CSRF token is a combination of the base64-encoded hash and the original message, separated by a colon (:).
sessionID should be empty if user is not authenticated.
func (*Manager) Hash ¶
Hash computes the HMAC SHA-256 hash of the given message using the Manager secret.
func (*Manager) Middleware ¶
Middleware is an HTTP middleware that provides CSRF protection.
func (*Manager) VerifyToken ¶
VerifyToken checks the validity of the given CSRF token.
type ManagerOption ¶
type ManagerOption func(m *Manager)
func WithCookieOpts ¶
func WithCookieOpts(cookieOpts CookieOptions) ManagerOption
func WithErrorHandler ¶
func WithErrorHandler(errorHandler http.Handler) ManagerOption
func WithHeaderName ¶
func WithHeaderName(headerName string) ManagerOption
func WithTrustedOrigins ¶
func WithTrustedOrigins(trustedOrigins []string) ManagerOption