我正在尝试在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)
登录
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
答案 0 :(得分:2)
重要的是,您应该检查所有错误 - 例如:
- 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)
答案 1 :(得分:0)
如果您正在寻找使用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中间件包装后,后续请求将自动进行身份验证。该库在构建时考虑到了简单性,是对现有库的替代。
有关使用和功能的更多详细信息,请参见自述文件: