dqm7854 2018-09-11 12:11
浏览 56

无法获取大猩猩会话。按键值

The problem is, cannot get value from session.Value in another file in the same package

In the controllers.go file

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)
        }

    }
}

IN middleware.go file in the same package

 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()))

What I have done wrong? Why session.Values["authenticated"] returns "nil"

  • 写回答

1条回答 默认 最新

  • dsa1230000 2018-09-11 13:30
    关注

    session, _ := store.Get(r, "session") //SESSION START, your session depends on the request r, which is a pointer that is created by the package that calls your controller. If you are calling session from another file, you need to ensure, that it is the same request that is passed into store.Get(). That could be the reason.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看