Skip to content

CSRF validation fails on HTTP (localhost dev) with gorilla/csrf v1.7.3 - Origin scheme mismatch #1

@syswave-dev

Description

@syswave-dev

Running LightCMS locally over HTTP with secure_cookies: false results in 403 "Invalid or missing CSRF token" on every POST to /cm/login.

Root cause: gorilla/csrf v1.7.x defaults the request URL scheme to https for Origin validation unless the request context is explicitly marked plaintext. The browser sends Origin: http://localhost:8082, the middleware compares against https://localhost:8082, scheme mismatch → ErrBadOrigin. csrf.Secure(false) only controls the cookie's Secure flag, not the Origin check.

Fix: When cfg.SecureCookies is false, wrap the CSRF middleware to mark every request as plaintext via csrf.PlaintextHTTPRequest(r) before validation runs:

if !cfg.SecureCookies {
    inner := csrfMiddleware
    csrfMiddleware = func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            inner(next).ServeHTTP(w, csrf.PlaintextHTTPRequest(r))
        })
    }
}

This goes right after the csrf.Protect(...) block and before admin.Use(csrfMiddleware). Production with SecureCookies=true is unaffected.

Environment: Ubuntu 22.04, Go 1.24, local MongoDB 7.0 (replica set), LightCMS v6.0.2

Note: Root cause was identified with the help of Claude Code, which analyzed the gorilla/csrf middleware chain in the codebase.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions