sessions icon indicating copy to clipboard operation
sessions copied to clipboard

Session still exists after setting MaxAge = -1

Open Hitan999 opened this issue 2 years ago • 0 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Current Behavior

I wrote Gorilla Sessions to manage login and logout sessions a platform, and I attach below the code for the logout, which is based on setting MaxAge = -1 in the current session. However, it looks like setting MaxAge to -1 does not delete the session, and I am confused about what is happening.

Store is initialized:

package sessionstore

import (
	"github.com/gorilla/sessions"
)

// Initializes the Sessions cookie store.
var Store = sessions.NewCookieStore([]byte("key"))

For logging out, the function first reads the existing session:

// Checks the session in the cookies, or creates a new one.
session, err := sessionstore.Store.Get(r, "session")
if err != nil {
	http.Error(w, err.Error(), http.StatusInternalServerError)
	fmt.Println("Error with session check")
}

then prints the session details, changes MaxAge to -1, and saves the new session:

if !session.IsNew {
	// Print MaxAge
	fmt.Printf("MaxAge: %d\n", session.Options.MaxAge)
		
	// Print Secure
	fmt.Printf("Secure: %t\n", session.Options.Secure)
	
	// Print HttpOnly
	fmt.Printf("HttpOnly: %t\n", session.Options.HttpOnly)
	
	// Sets the MaxAge to a negative value to expire the session.
	session.Options = &sessions.Options{
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
		Secure:   true,
		SameSite: http.SameSiteNoneMode,
		Domain:   ".example.com", 
	}

	// Saves the session to apply the changes.
	err := session.Save(r, w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		fmt.Println("Error saving session after deletion")
	} else {
		result = "OK"
	}

I then re-read the session and check if the options have been saved correctly, and they do. But it looks that the session is not really deleted straight away, or it would not be able to read the session after the save. Moreover, when the first part of the code reads the session, it gives "false" to Secure and HttpOnly, although during login process the session was created with the same Options (e.g. "true").

If I now remove the other options (Secure, etc.) the cookie will not match with the cookie in the browser, thus will not be set to expired, and refreshing the sessions will still look active. The check of the session will also show that MaxAge is back to 3600.

Could someone say what is happening, and probably where I am making mistakes?

Expected Behavior

No response

Steps To Reproduce

No response

Anything else?

No response

Hitan999 avatar Dec 27 '23 16:12 Hitan999