Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not expire a cookie

Tags:

cookies

go

I'm playing with the Go App Engine SDK and I'm trying to set/expires Cookies.

There is no problem by setting a Cookie, but it is impossible to make it expiring in the browser.

The app is a based on a negroni instance:

func init() {

    app := negroni.New()
    app.UseHandler(Router())
    http.Handle("/", app)

}

The router is a mux instance:

func Router() *mux.Router {

    r := mux.NewRouter()
    subRouter := r.PathPrefix(PATH_PREFIX).Subrouter()

    subRouter.HandleFunc("/sign", LoginHandler)
    subRouter.HandleFunc("/userinfo", UserInfo)
    subRouter.HandleFunc("/logout", Logout)

    return r
}

The login handler is basic:

func LoginHandler(w http.ResponseWriter, r *http.Request) {

    ctx := appengine.NewContext(r)

    u := user.Current(ctx)

    if u == nil {

        url, err := user.LoginURL(ctx, r.URL.String())
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        w.Header().Set("Location", url)
        w.WriteHeader(http.StatusFound)
        return
    }

    //COOKIE_ID = "SomeString"
    cookie := &http.Cookie{Name: COOKIE_ID, Value: u.ID, Path: "/", MaxAge: 0}
    http.SetCookie(w, cookie)

    w.Header().Set("Location", "/")
    w.WriteHeader(http.StatusFound)
}

To expires the cookie:

func Logout(w http.ResponseWriter, r *http.Request) {

    ctx := appengine.NewContext(r)
    url, err := user.LogoutURL(ctx, "/")

    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    expiredCookie := &http.Cookie{Name: COOKIE_ID, MaxAge: -10, Expires: time.Now()}
    http.SetCookie(w, expiredCookie)

    w.Header().Set("Location", url)
    w.WriteHeader(http.StatusFound)
}

I tried everything:

  • Getting the old cookie, change MaxAge and Expires
  • Create a new cookie with the same Name to overwrite

Full code: https://gist.github.com/yageek/78e43c83b56467fc8338

In any case, the cookie still remains in the navigator. What do I do wrong ?

like image 899
yageek Avatar asked Jan 08 '23 02:01

yageek


1 Answers

Browsers store cookies for multiple paths. Set the path attribute on the cookie header to match the path attribute used to create the cookie.

Set maximum age to a negative value to clear the cookie. The maximum age attribute is not set on the header if equal to zero.

Some browsers do not understand the maximum age attribute. Set expiration to a time in the past for the benefit of those browsers.

expiredCookie := &http.Cookie{Path: "/", Name: COOKIE_ID, MaxAge: -1, Expires: time.Now().Add(-100 * time.Hour)}
like image 70
Bayta Darell Avatar answered Feb 23 '23 11:02

Bayta Darell