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

net/http auth 方法不稳定

net/http auth 方法不稳定

Go
慕码人8056858 2023-06-12 19:12:05
我制作了自己的身份验证(和单会话身份验证)方法,将会话保存到 redis,该方法是:我检查,浏览器是否有来自我的服务器的 cookie,如果没有,则创建并保存在浏览器中检查redis上是否存在cookie id,如果是,下一步如果不重定向到登录以cookie id 为key 检查redis 值是什么,该值将是用户名,如果用户名存在,则通过用户名检查redis 中的值,如果用户名有cookie id 值,然后比较,cookie id 是否与当前浏览器id 相同,如果不是,重定向到登录代码请求前:func (hs BeforeRequest) ServeHTTP(w http.ResponseWriter, r *http.Request) {    if !strings.Contains(r.RequestURI, "/login") && !strings.Contains(r.RequestURI, "/logout") {        // Check is user has `guid` cookie        Guid, err := r.Cookie("guid")        // if cookie not available, set cookie and redirect to login        if err != nil {            // Set the cookie            expiration := time.Now().Add(365 * 24 * time.Hour)            cookie := http.Cookie{Name: "guid", Value: helper.GenerateGuid(), Expires:expiration}            http.SetCookie(w, &cookie)            // Redirect to login            http.Redirect(w, r, "/login", 301)            return        } else {            // Return username that used by user (by it's Guid)            _, err := redisdb.Get(Guid.Value).Result()            if err != redis.Nil {                // Get active Guid by username, return active Guid                UsedFor, err := redisdb.Get(IsHasRedis).Result()                if err != redis.Nil && err == nil {                    if UsedFor != Guid.Value {                        fmt.Println("this account used in another session")                        http.Redirect(w, r, "/login", 301)                        return                    }                } else {                    // definitely not logged in                    http.Redirect(w, r, "/login", 301)                    return                }            } 问题是,这个 auth 方法不稳定,idk 为什么但是在用户成功登录之后:access /blog 重定向到登录访问/博客(打开开发者工具)工作访问/设置工作几分钟/几小时后,访问 /settings 重定向到 /login我登录,成功,访问/settings,再次重定向到/login是的,只是不稳定笔记 :我使用“github.com/julienschmidt/httprouter”进行路由“github.com/go-redis/redis” 用于 redis
查看完整描述

1 回答

?
莫回无

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

301 响应状态意味着 Moved Permanently,允许浏览器无限期地缓存响应。使用 302 Found 代替重定向,或者根本不重定向(您可以立即提供登录页面)。

打开开发人员工具很可能会禁用缓存,使其正常工作。


查看完整回答
反对 回复 2023-06-12
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

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