Gorilla 会话在 Golang 中不存在

问题描述 投票:0回答:2

我在使用 Gorilla 会话处理程序在 Golang 中保留会话时遇到问题。其他堆栈溢出问题中也提出了类似的问题(未解决!)(此处:使用 gorilla 会话时未保存 golang 中的会话变量和此处:无法通过密钥获取 gorilla 会话值)。这非常可怕,因为看起来 1) 不仅仅是我 2) 目前似乎没有解决方案 3) Gorilla Sessions 包可能从根本上被破坏了。

这是更详细的问题:

我可以在登录时设置会话没有问题。但是,在我登录并向后端发出另一个请求后,会话值不会持久化,这意味着我无法拉出 session.Value['username'] 例如(甚至尽管这是会议的重点)。

所以:

A)登录,写入会话,检索 session.Value['usernames'] ,它工作正常。

B) 导航到前端的另一个页面并向后端再次发出请求(创建一个新角色)。

C) 尝试检索 session.Value['username']。没有啊!!!

这是用户在后端导航登录的流程 -

首先是会话处理程序:

package config

import (
    "log"
    "net/http"

    "github.com/gorilla/sessions"
)

type Options struct {
    Path     string
    Domain   string
    MaxAge   int
    Secure   bool
    HttpOnly bool
}

type Session struct {
    ID      string
    Values  map[interface{}]interface{}
    Options *Options
    IsNew   bool
}

type Store interface {
    Get(r *http.Request, name string) (*sessions.Session, error)
    New(r *http.Request, name string) (*sessions.Session, error)
    Save(r *http.Request, w http.ResponseWriter, s *sessions.Session) error
}

var SessionsStore = sessions.NewCookieStore([]byte("secret"))

func init() {
    SessionsStore.Options = &sessions.Options{
        Domain:   "localhost",
        Path:     "/",
        MaxAge:   3600 * 8, // 8 hours
        HttpOnly: true,
    }
}

func KeyStore() (store Store) {

    log.Print("inside KeyStore")
    store = SessionsStore
    log.Print("Value of store is : ", store)
    return store
}

接下来,这是我如何从 main 到每个组件的路由:

主要

package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"
    "os"

    _ "github.com/lib/pq"
    "github.com/patientplatypus/gorest/config"

    "github.com/gorilla/handlers"
)

const (
    host     = "localhost"
    port     = 5432
    user     = "patientplatypus"
    password = "superdupersecretyo"
    dbname   = "dungeon_world"
)

func main() {

    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        "localhost", 5432, "patientplatypus", "supersecret", "dungeon_world")
    var err error
    config.DB, err = sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }

    err = config.DB.Ping()
    if err != nil {
        panic(err)
    }

    fmt.Println("Successfully connected~!")

    router := NewRouter()
    os.Setenv("ORIGIN_ALLOWED", "*")
    headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
    originsOk := handlers.AllowedOrigins([]string{os.Getenv("ORIGIN_ALLOWED")})
    methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

    log.Fatal(http.ListenAndServe(":8080", handlers.CORS(originsOk, headersOk, methodsOk)(router)))

}

这是路由到每个处理程序的路由包:

package main

import (
    "net/http"

    "github.com/patientplatypus/gorest/users"

    "github.com/patientplatypus/gorest/dungeon_db"

    "github.com/patientplatypus/gorest/character"

    "github.com/patientplatypus/gorest/createcharacter"

    "github.com/gorilla/mux"
)

type Route struct {
    Name        string
    Method      string
    Pattern     string
    HandlerFunc http.HandlerFunc
}

type Routes []Route

func NewRouter() *mux.Router {

    router := mux.NewRouter().StrictSlash(true)
    for _, route := range routes {
        router.
            Methods(route.Method).
            Path(route.Pattern).
            Name(route.Name).
            Handler(route.HandlerFunc)
    }

    return router
}

var routes = Routes{
    Route{
        "ClassType",
        "POST",
        "/character/class",
        character.ClassType,
    },
    <MORE ROUTES FOLLOWING SAME PATTERN>
}

现在这是登录功能。这是我编写原始会话并打印出 session.Values['username'] 以表明它有效的地方:

package users

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/patientplatypus/gorest/config"
)

type LoginResponse struct {
    Status string
}

type User struct {
    Username string
    Password string
    Id       int
}

func UserLogin(w http.ResponseWriter, r *http.Request) {

    decoder := json.NewDecoder(r.Body)

    var incomingjson User
    err := decoder.Decode(&incomingjson)

    if err != nil {
        panic(err)
    }

    username := incomingjson.Username
    password := incomingjson.Password

    log.Print("username: ", username)
    log.Print("password: ", password)
    if username != "" && password != "" {
        incomingjson.Login(w, r)
    } else {
        fmt.Fprintln(w, "error username or password is blank!")
    }
}

func (incomingjson *User) Login(w http.ResponseWriter, r *http.Request) {
    session, _ := config.KeyStore().Get(r, "cookie-name")
    log.Print("loginjson: ", incomingjson)
    var tempvar string

    err := config.DB.QueryRow("SELECT username FROM users WHERE username=$1;", incomingjson.Username).Scan(&tempvar)
    log.Print("err: ", err)
    if err == nil {
        // 1 row
        log.Print("Found username")
        var passwordindatabase string
        config.DB.QueryRow("SELECT password FROM users WHERE username=$1;", &incomingjson.Username).Scan(&passwordindatabase)
        if passwordindatabase == incomingjson.Password {
            log.Print("username and password match!")
            session.Values["authenticated"] = true
            session.Values["username"] = incomingjson.Username
            config.KeyStore().Save(r, w, session)
            response := LoginResponse{Status: "Success, user logged in"}
            json.NewEncoder(w).Encode(response)
        } else {
            log.Print("username and password don't match!")
            session.Values["authenticated"] = false
            session.Values["username"] = ""
            config.KeyStore().Save(r, w, session)
            response := LoginResponse{Status: "Failure, username and password don't match"}
            json.NewEncoder(w).Encode(response)
        }
    } else {
        //empty result or error
        log.Print("Username not found or there was an error: ", err)
        response := LoginResponse{Status: "User not found!"}
        json.NewEncoder(w).Encode(response)
    }
}

现在这是问题所在。它的工作是在检查用户存在后创建一个新角色(sessioncheck 可以)...

所以我在这里:

package createcharacter

import (
    "encoding/json"
    "log"
    "net/http"

    "github.com/patientplatypus/gorest/config"
)

var Username string
var Checkok bool


func SessionsCheck(w http.ResponseWriter, r *http.Request) (username string, checkok bool) {
    store := config.KeyStore()
    session, _ := store.Get(r, "cookie-name")
    log.Print("inside sessionscheck...what is the value of stuff....")
    log.Print("session: ", session)
    log.Print("session.Values: ", session.Values)
    log.Print("username: ", session.Values["username"])
    log.Print("authenticated: ", session.Values["authenticated"])
    if session.Values["username"] == nil {
        if session.Values["authenticated"] == false {
            log.Print("Verboten!")
            http.Error(w, "Forbidden", http.StatusForbidden)
            return "nil", false
        }
    }
    return session.Values["username"].(string), true
}

func NewCharacter(w http.ResponseWriter, r *http.Request) {
    Username, Checkok = SessionsCheck(w, r)
    <FUNCTION CONTINUES>

这就是我收到错误的地方......但我不知道如何修复。

终端输出为:

2017/10/15 15:08:56 inside KeyStore
2017/10/15 15:08:56 Value of store is : &{[0xc42010c000] 0xc42007d5f0}
2017/10/15 15:08:56 inside sessionscheck...what is the value of stuff....
2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
2017/10/15 15:08:56 session.Values: map[]
2017/10/15 15:08:56 username: <nil>
2017/10/15 15:08:56 authenticated: <nil>
2017/10/15 15:08:56 http: panic serving [::1]:53668: interface conversion: interface {} is nil, not string
goroutine 13 [running]:
net/http.(*conn).serve.func1(0xc42015c5a0)
    /usr/local/opt/go/libexec/src/net/http/server.go:1697 +0xd0
panic(0x133bcc0, 0xc420061f00)
    /usr/local/opt/go/libexec/src/runtime/panic.go:491 +0x283
github.com/patientplatypus/gorest/createcharacter.SessionsCheck(0x1540d00, 0xc42010a540, 0xc42014ea00, 0xc42011ab00, 0x3, 0xc420001680)
    /Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:31 +0x5c9
github.com/patientplatypus/gorest/createcharacter.NewCharacter(0x1540d00, 0xc42010a540, 0xc42014ea00)
    /Users/patientplatypus/Documents/golang/src/github.com/patientplatypus/gorest/createcharacter/charactercontroller.go:35 +0x5a
net/http.HandlerFunc.ServeHTTP(0x13b8690, 0x1540d00, 0xc42010a540, 0xc42014ea00)
    /usr/local/opt/go/libexec/src/net/http/server.go:1918 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc420066360, 0x1540d00, 0xc42010a540, 0xc42014ea00)
    /Users/patientplatypus/Documents/golang/src/github.com/gorilla/mux/mux.go:133 +0xed
github.com/gorilla/handlers.(*cors).ServeHTTP(0xc42010c7e0, 0x1540d00, 0xc42010a540, 0xc42014e800)
    /Users/patientplatypus/Documents/golang/src/github.com/gorilla/handlers/cors.go:118 +0x5c8
net/http.serverHandler.ServeHTTP(0xc42014a000, 0x1540d00, 0xc42010a540, 0xc42014e800)
    /usr/local/opt/go/libexec/src/net/http/server.go:2619 +0xb4
net/http.(*conn).serve(0xc42015c5a0, 0x1541240, 0xc420061dc0)
    /usr/local/opt/go/libexec/src/net/http/server.go:1801 +0x71d
created by net/http.(*Server).Serve
    /usr/local/opt/go/libexec/src/net/http/server.go:2720 +0x288

对于冗长的内容,我感到抱歉,但我认为这是我可以从我的代码库中重现的最小示例。如果有人有任何建议请告诉我。

编辑:

我注意到的一件事如下:

2017/10/15 15:08:56 session: &{ map[] 0xc4201316b0 true 0xc4200e0a80 cookie-name}
2017/10/15 15:08:56 session.Values: map[]

似乎表明用户名和经过身份验证的(true 0xc4200e0a80)正在存储在 session.Values []map 函数的外部。这是为什么?

编辑编辑:

所以...我认为我编写 config.KeyStore() 的方式可能是一个问题,所以我将其重写为以下内容,并将其保留在整个项目中:

package config

import (
    "github.com/gorilla/sessions"
)

var SessionsStore = sessions.NewCookieStore([]byte("secret"))

func init() {
    SessionsStore.Options = &sessions.Options{
        Domain:   "localhost",
        Path:     "/",
        MaxAge:   3600 * 8, // 8 hours
        HttpOnly: true,
    }
}

所以现在只要我需要 SessionsStore,我就调用 conf.SessionsStore。这似乎是我认为可能的规范方法。我还是有同样的问题。

session go gorilla
2个回答
1
投票
package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/gorilla/mux"
    "github.com/gorilla/sessions"
)

const appCookie = "myappcookies"

var cookies *sessions.CookieStore

func Login(w http.ResponseWriter, r *http.Request) {
    //
    // For the sake of simplicity, I am using a global here. 
    // You should be using a context.Context instead!
    session, err := cookies.Get(r, appCookie)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        log.Println(err)
        return
    }
    session.Values["userName"] = "StackOverflow"
    session.Save(r, w)
}

func Session(w http.ResponseWriter, r *http.Request) {
    session, err := cookies.Get(r, appCookie)
    if err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        log.Println(err)
        return
    }
    w.Write([]byte(fmt.Sprintf("Objects in session: %d\n", len(session.Values))))
    for k, v := range session.Values {
        w.Write([]byte(fmt.Sprintf("Key=%v, Value=%v\n", k, v)))
    }
}

func main() {
    cookies = sessions.NewCookieStore([]byte("mysuperdupersecret"))
    router := mux.NewRouter()
    router.Path("/login").Methods(http.MethodPost).HandlerFunc(Login)
    router.Path("/session").Methods(http.MethodGet).HandlerFunc(Session)
    server := &http.Server{
        Handler: router,
        Addr:    ":8000",
        // Good practice: enforce timeouts for servers you create!
        WriteTimeout: 15 * time.Second,
        ReadTimeout:  15 * time.Second,
    }
    log.Fatal(server.ListenAndServe())
}

0
投票

首先,检查客户端是否保存了 cookie。检查浏览器 > 存储 > Cookie。 如果客户端正在获取 cookie,请记住在客户端请求中启用凭据。

fetch("http://example.com/data.json", {
       credentials: "include"
})

查看更多信息:https://sabe.io/blog/javascript-pass-cookies-fetch-axios

© www.soinside.com 2019 - 2024. All rights reserved.