gocookies

Go Gin ctx.SetCookie can't clear cookie for a specific domain


I got a strange case when using go Gin, I got a site with this address: https://opencsg-stg.com

I want to clear the cookies to let user logout when user access this path /logout

so in my Gin code I do it like this:

    for _, cookie := range cookies {
        ctx.SetCookie(cookie.Name, "", -1, "/", "opencsg-stg.com", false, false)
    }

But it's not working, when I check the headers in browser, it looks like this:

enter image description here

When I changed the code to this:

    for _, cookie := range cookies {
        ctx.SetCookie(cookie.Name, "", -1, "/", "", false, false)
    }

it works and the headers in browser is like this: enter image description here

Not sure why it is working, anyone knows?


Solution

  • TL;DR

    Evidence suggests that the cookie(s) you're trying to clear were not created with a Domain attribute. In that case, to effectively clear those cookies, you must set them without specifying any Domain attribute.

    More details

    Cookies are identified by the following triplet: (name, domain, path). Note that "domain" is tricky: every cookie is associated with a domain, but that doesn't mean it was created with a Domain attribute. Even with all other things being equal, a cookie created with a Domain attribute is different from a cookie created without one. For instance,

    Set-Cookie: can-change-username=true; Path=/; Domain=opencsg-stg.com
    Set-Cookie: can-change-username=true; Path=/
    

    creates two distinct cookies in the browser.

    Check in your backend code whether those cookies are created with or without a Domain attribute. You can also check this in the browser: the DevTools use a leading . in the value of the Domain column as a visual indicator that a cookie was created with a Domain attribute.