Cookie not updating on client

Okay so let’s start with the code:

// LoginHandler Handles requests for logging into Services
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		t, _ := template.ParseFiles("Templates/contentlayout.html", "Templates/publicnav.html", "Templates/login.html")
		t.Execute(w, "Login Page!")
	case "POST":
		r.ParseForm()
		user := data.User{}
		user.GetUser(r.PostFormValue("email"))
		if user.Password == r.PostFormValue("password") {
			WebUtils.ServeToken(w, r, &user)
			http.Redirect(w, r, "/dashboard/"+user.UUID, 301)
		} else {
			fmt.Fprintf(w, "Failed to Login user: %v", user.Name)
		}
	}
}

// LogoutHandler answers requests to logout, by destroying user's authToken
func LogoutHandler(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("access_token")
	if err == http.ErrNoCookie {
		fmt.Fprint(w, "No such authentication cookie!")
	} else {
		fmt.Println("Setting Cookie Values")
		cookie.Value = "0"
		cookie.MaxAge = -1
		cookie.Expires = time.Unix(1, 0)
		fmt.Printf("Cookie values changed: %v", cookie.String())
		http.SetCookie(w, cookie)

		http.Redirect(w, r, "/", 301)
	}
}

And the ServeToken function that’s called during Login to set the initial cookie:

// ServeToken creates JSON Web Token with user claims and attaches it to Cookie Header
func ServeToken(w http.ResponseWriter, r *http.Request, u *data.User) {
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"name":  u.Name,
		"email": u.Email,
		"exp":   time.Now().Add(time.Minute * 10).Unix(),
	})

	authToken, err := token.SignedString([]byte("secret"))
	if err != nil {
		log.Panic(err)
	} else {
		maxduration := 5 * 60
		cookie := http.Cookie{Name: "access_token", Value: authToken, Path: "/", MaxAge: int(maxduration), HttpOnly: true}
		http.SetCookie(w, &cookie)
	}
}

My problem is that I am trying to destroy the cookie to get the user logged out, since I am presently only handling my session with a JWT cookie, there is nothing to invalidate on the server side to log them out. If this cookie continues to persist it won’t keep them from accessing the site until it’s gone by means of natural expiration, which works.

I’m just wondering why the cookie is not updated when I write it again, any help would be greatly appreciated.

Hi,

Use another 3xx code, 303 is better.
Code 301 your browser cache http response for Logout request.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.