我正在尝试在 golang 中验证用户(使用电子邮件和密码),但我在会话方面遇到了一些问题。似乎我无法从/login/到/(主页)页面检索会话值。
用户注册
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(r.Form["passwordSignup"][0]), bcrypt.DefaultCost)
err = c.Insert(&model.UserModel{
Email: r.Form["emailSignup"][0],
Password: string(hashedPassword),
CreatedAt: time.Now(),
})
// TODO : should session management be made in here ???
// you can use gorilla sessions if you want as far it works
http.SetCookie(w, cookie)
http.Redirect(w, r, "/", 301) // goes to the homepage(only accessed by authenticated users)
Run Code Online (Sandbox Code Playgroud)
登录
if r.Form["emailLogin"][0] == result.Email
&& bcrypt.CompareHashAndPassword([]byte(result.Password), []byte(r.Form["passwordLogin"][0])) == nil {
// TODO : Handling the session in here
http.Redirect(w, r, "/", 301) // goes to the home page
} else {
http.Redirect(w, r, "/login/", 301)
}
Run Code Online (Sandbox Code Playgroud)
我也检查了此链接: http://shadynasty.biz/blog/2012/09/05/auth-and-sessions/ https://www.youtube.com/watch?v=p0tGnjW_xxI
重要的是,您应该检查所有错误 - 例如:
- hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(r.Form["passwordSignup"][0]), bcrypt.DefaultCost)
# Check our error, especially for something as important as password hashing
+ hashedPassword, err := bcrypt.GenerateFromPassword([]byte(r.Form["passwordSignup"][0]), bcrypt.DefaultCost)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
Run Code Online (Sandbox Code Playgroud)
很多相关的 cookie 代码都丢失了,但它应该是这样的:
cookie := &http.Cookie{
Name: "my_app",
Value: val, // Some encoded value
Path: "/", // Otherwise it defaults to the /login if you create this on /login (standard cookie behaviour)
MaxAge: 86400, // One day
}
http.SetCookie(w, cookie)
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用gorilla/sessions(我推荐它,因为它可以正确验证 cookie),您可以执行以下操作:
session, err := store.Get(r, "session-name")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
session.Options.Path = "/"
session.Values["user"] = user
err := session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
http.Redirect(w, r, "/", 301)
Run Code Online (Sandbox Code Playgroud)