go - 注销后如何停止会话缓存经过身份验证的用户数据
问题描述
这段代码在 这里被利用
下面的代码用于在 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)
}
解决方案
恐怕如果不使用 JavaScript 并在离开之前更改“秘密”页面,就无法“修复”您的代码。
问题不在 Go 中,或者在 中gorilla/sessions
,甚至在 HTTP 中:它是 Web 浏览器执行缓存的方式:至少在 Firefox 和 Chrome 中,当“后退”和“前进”时,浏览器只显示缓存的页面磁盘,完全忽略标题。
哦,顺便说一句:要尝试强制浏览器停止缓存页面,您应该将这些行添加到“秘密”处理程序,而不是“注销”处理程序。
推荐阅读
- php - 单击按钮时输出消息,然后在一段时间后自动消失
- react-native - 为 React Native 安装 gRPC-Core 时出错
- windows - 有没有办法在 MS Windows perl 中打开包含长文件名的文件夹?
- node.js - 无法使用 Typescript 从 Protractor 中的节点连接读取描述符
- intellij-idea - IntelliJ 远程调试有时不起作用
- dm-script - 如何在堆栈图像的每一帧中添加注释信息?
- c++ - 在 C++ 中返回函子的正确方法
- git - 获取在上次发布的特定日期或任何提交 ID 之前更改的文件列表
- android - 使用 Flutter 共享插件共享文件时出现 PlatformException
- flutter - 如何在 Flutter Web 上播放本地 mp3?