Gin框架下如何获取登录的session?

我的中间件获取不到Login登录后保存的session.
我参考的是gin-auth-example.

main函数, 代码如下,

  func main() {
    r := gin.Default()
    sess := r.Group("/", pkg.EnableCookieSession())
    {
        sess.POST("/login", post.Login)

        /*
         * Got problem here, session not working...
         */
        authorized := sess.Group("/auth", pkg.AuthSessionMiddle)
        {
            authorized.POST("/upload", post.Upload)
            authorized.POST("/webshell", post.WebShell)
            authorized.StaticFS("/download", http.Dir("download"))
        }
    }
    err := r.RunTLS(":3333", "server.crt", "server.key")
    if err != nil {
        log.Fatal("r.Run")
    }
}

pkg.EnableCookieSession()代码如下

  func EnableCookieSession() gin.HandlerFunc {
    store, err := sessions.NewRedisStore(10, "tcp", "localhost:6379", "", []byte("secret"))
    if err != nil {
        log.Fatalf("sessions.NewRedisStore: %v", err)
    }
    return sessions.Sessions("mysession", store)
}

Login函数, 代码如下,

  func Login(c *gin.Context) {
    pkg.SaveAuthSession(c, username)
    c.JSON(http.StatusOK, gin.H{"message": "Successfully authenticated user"})
}

pkg.SaveAuthSession()代码如下,

func SaveAuthSession(c *gin.Context, username string) {
    session := sessions.Default(c)
    session.Set("user", username)
    err := session.Save()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save session"})
    }
    c.JSON(http.StatusOK, gin.H{"message": "save session ok"})
}

pkg.AuthSessionMiddle代码如下,

func AuthSessionMiddle(c *gin.Context) {
    session := sessions.Default(c)
    sessionValue := session.Get("user")
    if sessionValue == nil {
        c.JSON(http.StatusUnauthorized, gin.H{
            "error": "Unauthorized",
        })
        c.Abort()
        return
    }
    c.Next()
    return
}

我在终端用redis-cli使用”KEYS *”命令可以查看到保存的session.
问题在”session := sessions.Default(c)”这里, 它似乎得不到Login保存的session.
通过调试, 我发现这里始终是空的。 而我在gin-auth-example同样的地方调试发现这个地方这个地方是有Login存储的session

请问我的问题出在哪? 十分感谢。

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!