From 01d7d4bc2884b66839d155817b2be014c0b8c7c1 Mon Sep 17 00:00:00 2001 From: jdysya <1912377458@qq.com> Date: Sat, 15 Feb 2025 13:29:42 +0800 Subject: [PATCH] =?UTF-8?q?feat(gateway):=20=E4=BC=98=E5=8C=96=E7=99=BB?= =?UTF-8?q?=E5=BD=95=E5=8A=9F=E8=83=BD=E5=B9=B6=E5=A2=9E=E5=BC=BA=E5=AE=89?= =?UTF-8?q?=E5=85=A8=E6=80=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 设置 Session 中间件的 MaxAge、HttpOnly、Secure 和 SameSite 属性 - 修改用户名密码校验逻辑,增加错误处理 - 使用 303 状态码替换 302 状态码进行重定向 - 优化错误提示信息,提升用户体验 --- gateway/main.go | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/gateway/main.go b/gateway/main.go index 178942a..e9cb80a 100644 --- a/gateway/main.go +++ b/gateway/main.go @@ -30,6 +30,12 @@ func main() { // 配置 Session 中间件 store := cookie.NewStore([]byte("secret")) + store.Options(sessions.Options{ + MaxAge: 86400 * 7, + HttpOnly: true, + Secure: false, // 如果是HTTPS需要设为true + SameSite: http.SameSiteLaxMode, // 允许跨站携带cookie + }) r.Use(sessions.Sessions("mysession", store)) // 登录页面 @@ -42,15 +48,18 @@ func main() { username := c.PostForm("username") password := c.PostForm("password") - // 简单的用户名密码校验 - if username == "admin" && password == "password" { + if username == "admin" && password == "123" { session := sessions.Default(c) session.Set("user", username) - session.Save() - c.Redirect(http.StatusFound, "/") - } else { - c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "Invalid credentials"}) + if err := session.Save(); err != nil { + logger.Errorf("Session保存失败: %v", err) + c.HTML(http.StatusInternalServerError, "login.html", gin.H{"error": "登录状态保存失败"}) + return + } + c.Redirect(http.StatusSeeOther, "/") // 改用303状态码 + return } + c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "用户名或密码错误"}) }) // 权限校验中间件