我正在尝试在golang中验证用户(使用电子邮件和密码),但我遇到了一些会话问题。好像我无法从/ login /到/(home)页面检索会话值。
用户注册
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)
登录
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)
}
我也检查了这个链接: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
}
很多相关的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)
或者,如果您使用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)
如果您正在寻找使用Redis或Memcache作为会话存储的简单会话管理解决方案,我建议使用Jeff(免责声明:我写了它)。
在对用户进行身份验证后,您只需添加其会话,如下所示:
func (s Server) Login(w http.ResponseWriter, r *http.Request) {
user = Authenticate(r)
if user != nil {
// Key must be unique to one user among all users
err := s.jeff.Set(r.Context(), w, user.Email)
// handle error
}
// finish login
}
一旦用Jeff中间件包装,后续请求将自动进行身份验证。该库的构建简单易用,是作为现有库的替代品而构建的。
有关使用和功能的更多详细信息,请参阅自述文件: