我制作了自己的身份驗證(和單會話身份驗證)方法,將會話保存到 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
net/http auth 方法不穩定
慕碼人8056858
2023-06-12 19:12:05