feat(gateway): 优化登录功能并增强安全性
- 设置 Session 中间件的 MaxAge、HttpOnly、Secure 和 SameSite 属性 - 修改用户名密码校验逻辑,增加错误处理 - 使用 303 状态码替换 302 状态码进行重定向 - 优化错误提示信息,提升用户体验
This commit is contained in:
parent
8b67f40103
commit
01d7d4bc28
@ -30,6 +30,12 @@ func main() {
|
|||||||
|
|
||||||
// 配置 Session 中间件
|
// 配置 Session 中间件
|
||||||
store := cookie.NewStore([]byte("secret"))
|
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))
|
r.Use(sessions.Sessions("mysession", store))
|
||||||
|
|
||||||
// 登录页面
|
// 登录页面
|
||||||
@ -42,15 +48,18 @@ func main() {
|
|||||||
username := c.PostForm("username")
|
username := c.PostForm("username")
|
||||||
password := c.PostForm("password")
|
password := c.PostForm("password")
|
||||||
|
|
||||||
// 简单的用户名密码校验
|
if username == "admin" && password == "123" {
|
||||||
if username == "admin" && password == "password" {
|
|
||||||
session := sessions.Default(c)
|
session := sessions.Default(c)
|
||||||
session.Set("user", username)
|
session.Set("user", username)
|
||||||
session.Save()
|
if err := session.Save(); err != nil {
|
||||||
c.Redirect(http.StatusFound, "/")
|
logger.Errorf("Session保存失败: %v", err)
|
||||||
} else {
|
c.HTML(http.StatusInternalServerError, "login.html", gin.H{"error": "登录状态保存失败"})
|
||||||
c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "Invalid credentials"})
|
return
|
||||||
}
|
}
|
||||||
|
c.Redirect(http.StatusSeeOther, "/") // 改用303状态码
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "用户名或密码错误"})
|
||||||
})
|
})
|
||||||
|
|
||||||
// 权限校验中间件
|
// 权限校验中间件
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user