问题是,无法从session.value中获取同一包中另一个文件中的值
在controllers.go文件中
func (c *AuthenticationControllers) AdminLogin() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
//AUTHENTICATION
if answer {
w.Write([]byte("Successful Authenticated!"))
//1* Create Session
session, _ := store.Get(r, "session") //SESSION START
///Here I've setted true
session.Values["authenticated"] = true//Successful Authenticated
sessionToken, _ := uuid.NewV4() //Generate session token
session.Values["userid"] = sessionToken.String()
session.Save(r, w)
//Redirect
http.Redirect(w, r, "/admin/application", 302)
} else {
//http.Redirect(w, r, "/login", 302)
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
}
}
}
同一包中的middleware.go文件
func (m *AuthenticationMiddleWares) RequiresLogin(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "session") //!!!
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
handler(w, r)
}
}
session.Values["authenticated"] //has nil value, but has to be true after authentification in order to get you access to the route
router.HandleFunc("/admin/applications", authMiddle.RequiresLogin(authContrl.Application()))
我做错了什么?为什么session.Values [“ authenticated”]返回“ nil”
答案 0 :(得分:0)
session, _ := store.Get(r, "session") //SESSION START
,您的会话取决于请求r
,该请求是由调用控制器的程序包创建的指针。如果要从另一个文件调用session
,则需要确保它与传递到store.Get()
的请求相同。那可能就是原因。