13

使用 gorilla 会话 Web 工具包时,不会跨请求维护会话变量。当我启动服务器并键入 localhost:8100/ 时,页面被定向到 login.html,因为会话值不存在。登录后,我在商店中设置会话变量,页面被重定向到 home.html。但是,当我打开一个新选项卡并键入 localhost:8100/ 时,该页面应该使用已存储的会话变量定向到 home.html,但该页面改为重定向到 login.html。以下是代码。

    package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
    "github.com/gocql/gocql"
    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
    "net/http"
    "time"
)

var store = sessions.NewCookieStore([]byte("something-very-secret"))

var router = mux.NewRouter()

func init() {

    store.Options = &sessions.Options{
        Domain:   "localhost",
        Path:     "/",
        MaxAge:   3600 * 1, // 1 hour
        HttpOnly: true,
    }
}
func main() {
    //session handling
    router.HandleFunc("/", SessionHandler)
    router.HandleFunc("/signIn", SignInHandler)
    router.HandleFunc("/signUp", SignUpHandler)
    router.HandleFunc("/logOut", LogOutHandler)
    http.Handle("/", router)
    http.ListenAndServe(":8100", nil)
}

//handler for signIn
func SignInHandler(res http.ResponseWriter, req *http.Request) {

    email := req.FormValue("email")
    password := req.FormValue("password")

    //Generate hash of password
    hasher := md5.New()
    hasher.Write([]byte(password))
    encrypted_password := hex.EncodeToString(hasher.Sum(nil))

    //cassandra connection
    cluster := gocql.NewCluster("localhost")
    cluster.Keyspace = "gbuy"
    cluster.DefaultPort = 9042
    cluster.Consistency = gocql.Quorum
    session, _ := cluster.CreateSession()
    defer session.Close()

    //select query
    var firstname string
    stmt := "SELECT firstname FROM USER WHERE email= '" + email + "' and password ='" + encrypted_password + "';"
    err := session.Query(stmt).Scan(&firstname)
    if err != nil {
        fmt.Fprintf(res, "failed")
    } else {
        if firstname == "" {
            fmt.Fprintf(res, "failed")
        } else {
            fmt.Fprintf(res, firstname)
        }
    }

    //store in session variable
    sessionNew, _ := store.Get(req, "loginSession")

    // Set some session values.
    sessionNew.Values["email"] = email
    sessionNew.Values["name"] = firstname

    // Save it.
    sessionNew.Save(req, res)
    //store.Save(req,res,sessionNew)

    fmt.Println("Session after logging:")
    fmt.Println(sessionNew)

}

//handler for signUp
func SignUpHandler(res http.ResponseWriter, req *http.Request) {

    fName := req.FormValue("fName")
    lName := req.FormValue("lName")
    email := req.FormValue("email")
    password := req.FormValue("passwd")
    birthdate := req.FormValue("date")
    city := req.FormValue("city")
    gender := req.FormValue("gender")

    //Get current timestamp and format it.
    sysdate := time.Now().Format("2006-01-02 15:04:05-0700")

    //Generate hash of password
    hasher := md5.New()
    hasher.Write([]byte(password))
    encrypted_password := hex.EncodeToString(hasher.Sum(nil))

    //cassandra connection
    cluster := gocql.NewCluster("localhost")
    cluster.Keyspace = "gbuy"
    cluster.DefaultPort = 9042
    cluster.Consistency = gocql.Quorum
    session, _ := cluster.CreateSession()
    defer session.Close()

    //Insert the data into the Table
    stmt := "INSERT INTO USER (email,firstname,lastname,birthdate,city,gender,password,creation_date) VALUES ('" + email + "','" + fName + "','" + lName + "','" + birthdate + "','" + city + "','" + gender + "','" + encrypted_password + "','" + sysdate + "');"
    fmt.Println(stmt)
    err := session.Query(stmt).Exec()
    if err != nil {
        fmt.Fprintf(res, "failed")
    } else {
        fmt.Fprintf(res, fName)
    }
}

//handler for logOut
func LogOutHandler(res http.ResponseWriter, req *http.Request) {
    sessionOld, err := store.Get(req, "loginSession")

    fmt.Println("Session in logout")
    fmt.Println(sessionOld)
    if err = sessionOld.Save(req, res); err != nil {
        fmt.Println("Error saving session: %v", err)
    }
}

//handler for Session
func SessionHandler(res http.ResponseWriter, req *http.Request) {

    router.PathPrefix("/").Handler(http.FileServer(http.Dir("../static/")))
    session, _ := store.Get(req, "loginSession")

    fmt.Println("Session in SessionHandler")
    fmt.Println(session)


    if val, ok := session.Values["email"].(string); ok {
        // if val is a string
        switch val {
        case "": {
            http.Redirect(res, req, "html/login.html", http.StatusFound) }
        default:
            http.Redirect(res, req, "html/home.html", http.StatusFound)
        }
    } else {
        // if val is not a string type
        http.Redirect(res, req, "html/login.html", http.StatusFound)
    }
}

有人可以告诉我我做错了什么。提前致谢。

4

5 回答 5

28

首先:你永远不应该使用 md5 来散列密码。阅读这篇文章了解原因,然后使用 Go 的bcrypt 包。您还应该参数化您的 SQL 查询,否则您可能会遭受灾难性的SQL 注入攻击。

无论如何:这里有几个问题需要解决:

  • 您的会话没有“坚持”是因为您将其设置Path/loginSession- 因此当用户访问任何其他路径(即/)时,会话对该范围无效。

您应该在程序初始化时设置会话存储并在那里设置选项:

var store = sessions.NewCookieStore([]byte("something-very-secret"))

func init() {

   store.Options = &sessions.Options{
    Domain:   "localhost",
    Path:     "/",
    MaxAge:   3600 * 8, // 8 hours
    HttpOnly: true,
}

您可能会设置更具体的路径的原因是,如果登录的用户始终位于子路由中,例如/accounts. 在你的情况下,这不是正在发生的事情。

我应该补充一点,Web Inspector 中的 Chrome 的“资源”选项卡(资源 > Cookie)对于调试此类问题非常有用,因为您可以看到 cookie 过期、路径和其他设置。

  • 你也在检查session.Values["email"] == nil,这是行不通的。Go 中的空字符串只是"",因为session.Values是 a map[string]interface{},所以您需要将值输入到字符串中:

IE

if val, ok := session.Values["email"].(string); ok {
      // if val is a string
      switch val {
             case "":
                 http.Redirect(res, req, "html/login.html", http.StatusFound)
             default:
                 http.Redirect(res, req, "html/home.html", http.StatusFound)
      }
    } else {
        // if val is not a string type
        http.Redirect(res, req, "html/login.html", http.StatusFound)
    }

我们处理“不是字符串”的情况,所以如果会话不是我们所期望的(客户端修改了它,或者我们的程序的旧版本使用了不同的类型),我们会明确说明程序应该做什么。

  • 保存会话时,您没有检查错误。

    sessionNew.Save(req, res)
    

... 应该:

    err := sessionNew.Save(req, res)
    if err != nil {
            // handle the error case
    }
  • SessionHandler 您应该在提供静态文件之前获取/验证会话(但是,您正在以一种非常迂回的方式进行操作):

    func SessionHandler(res http.ResponseWriter, req *http.Request) {
        session, err := store.Get(req, "loginSession")
        if err != nil {
            // Handle the error
        }
    
        if session.Values["email"] == nil {
            http.Redirect(res, req, "html/login.html", http.StatusFound)
        } else {
           http.Redirect(res, req, "html/home.html", http.StatusFound)
        }
        // This shouldn't be here - router isn't scoped in this function! You should set this in your main() and wrap it with a function that checks for a valid session.
        router.PathPrefix("/").Handler(http.FileServer(http.Dir("../static/")))
    }
    
于 2014-02-18T21:46:06.037 回答
6

问题是您在调用session.Save. 这可以防止标头被写入,从而防止您的 cookie 被发送到客户端。

session.Query您调用Fprintf响应之后的代码中,一旦此代码执行,调用sessionNew.Save基本上什么都不做。删除任何写入响应的代码,然后重试。

如果响应已经被写入,我猜大猩猩工具包的会话应该在调用 Save 时返回错误。

于 2015-02-11T07:54:55.047 回答
2

从评论链开始,请尝试Domain从会话选项中删除约束,或将其替换为可解析的 FQDN(/etc/hosts例如使用)。

这似乎是 Chromium 中的一个错误,其中未发送具有显式“localhost”域的 cookie。这个问题似乎并没有出现在 Firefox 中。

我能够让你的演示工作使用

store.Options = &sessions.Options{
    // Domain: "localhost",
    MaxAge:   3600 * 1, // 1 hour
    HttpOnly: true,
}
于 2014-02-19T04:20:16.437 回答
2

就我而言,问题是路径。我知道问题不是关于它,但是当你搜索谷歌时,这篇文章首先出现。因此,我以如下路径开始会话:

/usuario/login

所以路径设置为 /usuario,然后,当我从/cookie 发出另一个请求时,没有设置因为/ 与 /usuario 不同

我通过指定路径来修复它,我知道这应该很明显,但我花了几个小时才意识到它。所以:

&sessions.Options{
        MaxAge:   60 * 60 * 24,
        HttpOnly: true,
        Path:     "/", // <-- This is very important
    }

有关一般 cookie 的更多信息:https ://developer.mozilla.org/es/docs/Web/HTTP/Cookies

于 2019-10-25T15:46:49.893 回答
0

使用服务器端“FilesystemStore”而不是“CookieStore”来保存会话变量。另一种选择是将会话更新为请求的上下文变量,即,将会话存储在上下文中,并让浏览器在每个请求中传递它,使用 gorilla/context 包中的 context.Set()。

使用“CookieStore”对客户端来说很繁重,因为随着 cookie 中存储的信息量的增加,每个请求和响应都会通过网络传输更多信息。它的优点是不需要在服务器端存储会话信息。如果在服务器上存储会话信息不是限制,理想的方式应该是在服务器端“非 cookie”会话存储中存储登录和身份验证相关信息,并将令牌传递给客户端。服务器将维护令牌和会话信息的映射。“FilesystemStore”允许您执行此操作。

尽管“FilesystemStore”和“CookieStore”都实现了“Store”接口,但它们各自的“Save()”函数的实现略有不同。CookieStore.Save()FilesystemStore.Save()这两个函数的源代码将帮助我们理解为什么“CookieStore”不能持久化会话信息。FilesystemStore 的 Save() 方法除了将会话信息写入响应头之外,还将信息保存在服务器端会话文件中。在“CookieStore”实现中,如果浏览器无法将新修改的 cookie 从响应中发送到下一个请求,则请求可能会失败。在“FilesystemStore”实现中,提供给浏览器的令牌始终保持不变。会话信息在文件中更新,并在需要时根据请求令牌获取。

于 2017-09-13T06:31:57.250 回答