Golang和Gorilla Sessions – 缓存阻止了注销功能。

huangapple go评论83阅读模式
英文:

Golang & Gorilla Sessions - Cache Prevents Logout Functionality

问题

我已经构建了一个使用Go Gorilla sessions包的应用程序。一切看起来都很好,除了在注销时实现以下代码:

func logout(w http.ResponseWriter, r *http.Request) {
  session, _ := store.Get(r, "authsesh")
  session.Values["access"] = "denied"
  session.Save(r, w)
  http.Redirect(w, r, "/", 302)
  return
}

因为需要身份验证的页面被浏览器缓存了,所以在注销后仍然可以访问。有什么方法可以解决这个问题吗?有没有办法阻止浏览器缓存页面?如果我清除缓存并保留cookie,我可以看到注销已经产生了预期的效果,所以cookie没有问题。

英文:

I've built an application that uses the Go Gorilla sessions package. Everything seems fine, except when on logout I implement

func logout(w http.ResponseWriter, r *http.Request) {
  session, _ := store.Get(r, "authsesh")
  session.Values["access"] = "denied"
  session.Save(r, w)
  http.Redirect(w, r, "/", 302)
  return
}

Because the page requiring authentication is cached by the browser, it can still be accessed after logout. How can I get around that? Is there a way to prevent the browser from caching the page? There's nothing wrong with the cookie, if I clear the cache and keep the cookie I can see the logout has had the desired effect.

答案1

得分: 6

在你的处理程序中设置正确的缓存头:

w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Expires", time.Unix(0, 0).Format(http.TimeFormat))
w.Header().Set("Pragma", "no-cache")
w.Header().Set("X-Accel-Expires", "0")

请注意,我们设置了多个头部来适应代理和HTTP/1.0客户端。

你也可以将它们包装成中间件来应用:

func NoCache(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        // 设置头部
    }

    return http.HandlerFunc(fn)
}

// 在你的路由器中
http.Handle("/user-dashboard", NoCache(http.HandlerFunc(YourDashboardHandler)))

这样可以确保在处理程序中设置正确的缓存头部。

英文:

Set the correct cache headers in your handler(s):

w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Expires", time.Unix(0, 0).Format(http.TimeFormat))
w.Header().Set("Pragma", "no-cache")
w.Header().Set("X-Accel-Expires", "0")

Note that we set multiple headers to account for proxies and HTTP/1.0 clients.

You can wrap these into middleware you can apply as well:

func NoCache(h http.Handler) http.Handler) {
    fn := func(w http.ResponseWriter, r *http.Request) {
        // Set the headers
    }

    return http.HandlerFunc(fn)
}

// In your router
http.Handle("/user-dashboard", NoCache(http.HandlerFunc(YourDashboardHandler))

huangapple
  • 本文由 发表于 2016年1月29日 22:16:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/35086688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定