Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invalid Cookie should point to a recoverable state #356

Open
Davst opened this issue Sep 19, 2023 · 1 comment
Open

Invalid Cookie should point to a recoverable state #356

Davst opened this issue Sep 19, 2023 · 1 comment

Comments

@Davst
Copy link

Davst commented Sep 19, 2023

So, I know this mainly is a rest product of me having an old cookie left from traefik 1 oauth but as users really can get themselves into odd unexpected situations I believe there should be better error handling for the "Invalid cookie mac" state.

I found myself in a situation after upgrading my server where all my normal browsers just returned Not authenticated whatever I did. The logs showed me this was due to an invalid cookie and thus i had to clear site cookies to recover.

However for many users that aren't that tech savvy this is essentially an unrecoverable state, where simply throwing up a oauth login page would allow them to recover from it. IF not that, at least clearing that cookie or logging them out or such would be resonable as well.

My suggestion is to improve the handling for this or at least provide options for redirection to a recoverable state.

@ljluestc
Copy link

package main

import (
    "log"
    "net/http"
    "strings"
)

func clearInvalidCookie(w http.ResponseWriter, r *http.Request) {
    // Check for invalid cookie
    cookie, err := r.Cookie("auth_token")
    if err != nil || !isValidCookie(cookie) {
        // Invalid cookie detected, clear it
        http.SetCookie(w, &http.Cookie{
            Name:   "auth_token",
            Value:  "",
            Path:   "/",
            MaxAge: -1, // expires immediately
        })

        // Redirect the user to the login page
        http.Redirect(w, r, "/login", http.StatusFound)
        return
    }

    // Proceed with normal behavior if cookie is valid
    nextHandler(w, r)
}

func isValidCookie(cookie *http.Cookie) bool {
    // Check the validity of the cookie (example check, can be more complex)
    return strings.HasPrefix(cookie.Value, "valid_token")
}

func nextHandler(w http.ResponseWriter, r *http.Request) {
    // Your normal request handling
    w.Write([]byte("Welcome!"))
}

func main() {
    http.HandleFunc("/", clearInvalidCookie)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants