Search code examples
sessiongogorillago-echo

Echo sessions middleware not saving


I am trying to use the sessions middleware for the echo web framework. The middleware is essentially just a wrapper around gorilla/sessions tailored to work with echo.

I have basically just copied the example given in the documentation and extended it slightly.


e := echo.New()
e.Use(session.Middleware(sessions.NewCookieStore([]byte("Secret"))))

// Add the name "Steve" to the session
e.GET("/login", func(c echo.Context) error {
        sess, err := session.Get("session", c)
        if err != nil {
            return err
        }
        sess.Options = &sessions.Options{
            Path:     "/",
            MaxAge:   0,
            HttpOnly: false,
            Secure:   true,
        }
        sess.Values["name"] = "Steve"
        sess.Save(c.Request(), c.Response())
        return c.NoContent(http.StatusOK)
    })

    // Reply with the name saved in the session
    e.GET("/whoami", func(c echo.Context) error {
        sess, err := session.Get("session", c)
        if err != nil {
            return err
        }

        return c.JSON(http.StatusOK, sess.Values["name"])
    })

I expect to first visit /login to save the name to the session, and then visit /whoami and receive the name "Steve".

/login returns StatusOK as expected, but /whoami always returns null. Why isn't the name being saved to the session?


Solution

  • The issue is caused by settings session.Option.Secure = true.

    I am testing locally and not using HTTPS so the cookie is not being set.