首页 > 解决方案 > 注销后如何停止会话缓存经过身份验证的用户数据

问题描述

这段代码在 这里被利用

下面的代码用于在 Go 中创建用户会话。会话工作正常。

遇到的问题是,在用户注销后,如果我单击浏览器后退按钮。然后我仍然可以看到注销用户的详细信息。

我在这里利用了 stackoverflow 解决方案,但没有运气

堆栈溢出链接

我还在注销处理程序中添加了以下代码

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

这是代码

package main

import (
    "fmt"
    "net/http"
   "github.com/gorilla/sessions"
)

var (
    // key must be 16, 24 or 32 bytes long (AES-128, AES-192 or AES-256)
    key = []byte("super-secret-key")
    store = sessions.NewCookieStore(key)
)

func secret(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "cookie-name")

    // Check if user is authenticated
    if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
        http.Error(w, "Forbidden", http.StatusForbidden)
        return
    }

    // Print secret message
    fmt.Fprintln(w, "The cake is a lie!")
        fmt.Fprintln(w, session.Values["foo"])
}

func login(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "cookie-name")

    // Authentication goes here

    // Set user as authenticated
  session.Values["authenticated"] = true
  session.Values["foo"] = "bar"
  session.Values[42] = 43
    session.Save(r, w)

fmt.Fprintln(w, session.Values["authenticated"])
fmt.Fprintln(w, session.Values["foo"])
fmt.Fprintln(w, session.Values["2"])
}

func logout(w http.ResponseWriter, r *http.Request) {
    session, _ := store.Get(r, "cookie-name")

    // Revoke users authentication
    session.Values["authenticated"] = false
        session.Values["foo"] = ""
        session.Values[42] = ""
    session.Save(r, w)

// prevent caching
w.Header().Set("Cache-Control", "no-cache, private, max-age=0")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("X-Accel-Expires", "0")


}

func main() {
    http.HandleFunc("/secret", secret)
    http.HandleFunc("/login", login)
    http.HandleFunc("/logout", logout)

    http.ListenAndServe(":8000", nil)
}

标签: go

解决方案


恐怕如果不使用 JavaScript 并在离开之前更改“秘密”页面,就无法“修复”您的代码。

问题不在 Go 中,或者在 中gorilla/sessions,甚至在 HTTP 中:它是 Web 浏览器执行缓存的方式:至少在 Firefox 和 Chrome 中,当“后退”和“前进”时,浏览器只显示缓存的页面磁盘,完全忽略标题。

哦,顺便说一句:要尝试强制浏览器停止缓存页面,您应该将这些行添加到“秘密”处理程序,而不是“注销”处理程序。


推荐阅读