为了账号安全,请及时绑定邮箱和手机立即绑定

Golang Cookie未删除

Golang Cookie未删除

Go
Helenr 2021-03-30 16:18:05
在尝试测试以下代码时://SetSingleSignOn Sets the cookie to allow for single sign cross applications.func SetSingleSignOn(w http.ResponseWriter, token string) {    http.SetCookie(w, &http.Cookie{        Name:     ssoCookie,        Value:    token,        Path:     "/",        HttpOnly: false,        Secure:   false,        Domain:   "localhost",        Expires:  time.Now().AddDate(0, 0, 7),        MaxAge:   0,    })}//DestroySingleSignOn Gets rid of single sign on, in case a user logs out of the application.func DestroySingleSignOn(r *http.Request, w http.ResponseWriter) {    cookie, err := r.Cookie(ssoCookie)    if err != nil || cookie.Value == "" {        return    }    cookie = &http.Cookie{        Name:     ssoCookie,        Path:     "/",        HttpOnly: false,        Secure:   false,        Domain:   "localhost",        Expires:  time.Now(),        MaxAge:   -1}    http.SetCookie(w, cookie)}我遇到了明显的错误失败。我所有的SetSingleSignOn通过测试,但健全性测试DestroySingleSignOn失败。好像http.SetCookie(w, cookie)根本没有调用过!更离奇的是,当我取消对函数的直接调用时http.SetCookie(w, &http.Cookie{    Name:     ssoCookie,    Path:     "/",    HttpOnly: false,    Secure:   false,    Domain:   "localhost",    Expires:  time.Now(),    MaxAge:   -1}它似乎可以正常工作(最后一个cookie处于非活动状态),但是现在其中有两个cookie res.Cookies()!是什么原因造成的?
查看完整描述

1 回答

?
一只萌萌小番薯

TA贡献1795条经验 获得超7个赞

在您的DestorySingleSignOn函数中,您将从以下代码块开始:


cookie, err := r.Cookie(ssoCookie)

if err != nil || cookie.Value == "" {

    return

}

请注意,您正在检查请求上的cookie ,但仅在response上设置了cookie 。您将需要发出请求以获取初始cookie集,然后使用该cookie发出第二个请求才能使它起作用。


t.Run("SignedOnFirst", func(t *testing.T) {


    req := httptest.NewRequest("POST",

        "localhost:42100",

        nil)

    w := httptest.NewRecorder()


    SetSingleSignOn(w, "12446rewa12314")


    // get the initial cookie

    res := w.Result()

    cookie := res.Cookies()[0]


    // issue a second request with the cookie

    req = httptest.NewRequest("POST",

        "localhost:42100",

        nil)

    req.AddCookie(cookie)

    w = httptest.NewRecorder()


    // assert.NotPanics(t, func() { DestroySingleSignOn(req, w) })

    DestroySingleSignOn(req, w)


    // get the new cookie

    res = w.Result()

    fmt.Println(res.Cookies())


    assert.Equal(t, 1, len(res.Cookies()))

    cookie = *res.Cookies()[0]

    // cookie should be named ssoCookie

    assert.Equal(t,

        ssoCookie,

        cookie.Name)


    // cookie should have already expired

    assert.True(t,

        time.Now().After(cookie.Expires))


})


查看完整回答
反对 回复 2021-04-19
  • 1 回答
  • 0 关注
  • 262 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信